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
/*
 * This file contains NDIS driver procedures, common for NDIS5 and NDIS6
 *
 * Copyright (c) 2008-2017 Red Hat, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met :
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and / or other materials provided with the distribution.
 * 3. Neither the names of the copyright holders nor the names of their contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#include "ndis56common.h"

#ifdef WPP_EVENT_TRACING
#include "ParaNdis-Common.tmh"
#endif

static void ReuseReceiveBufferRegular(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBuffersDescriptor);
static void ReuseReceiveBufferPowerOff(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBuffersDescriptor);

//#define ROUNDSIZE(sz) ((sz + 15) & ~15)
#define MAX_VLAN_ID     4095

#if 0
void FORCEINLINE DebugDumpPacket(LPCSTR prefix, PVOID header, int level)
{
    PUCHAR peth = (PUCHAR)header;
    DPrintf(level, ("[%s] %02X%02X%02X%02X%02X%02X => %02X%02X%02X%02X%02X%02X", prefix,
        peth[6], peth[7], peth[8], peth[9], peth[10], peth[11],
        peth[0], peth[1], peth[2], peth[3], peth[4], peth[5]));
}
#else
void FORCEINLINE DebugDumpPacket(LPCSTR prefix, PVOID header, int level)
{
}
#endif



/**********************************************************
Validates MAC address
Valid MAC address is not broadcast, not multicast, not empty
if bLocal is set, it must be LOCAL
if not, is must be non-local or local
Parameters:
    PUCHAR pcMacAddress - MAC address to validate
    BOOLEAN bLocal      - TRUE, if we validate locally administered address
Return value:
    TRUE if valid
***********************************************************/
BOOLEAN ParaNdis_ValidateMacAddress(PUCHAR pcMacAddress, BOOLEAN bLocal)
{
    BOOLEAN bLA = FALSE, bEmpty, bBroadcast, bMulticast = FALSE;
    bBroadcast = ETH_IS_BROADCAST(pcMacAddress);
    bLA = !bBroadcast && ETH_IS_LOCALLY_ADMINISTERED(pcMacAddress);
    bMulticast = !bBroadcast && ETH_IS_MULTICAST(pcMacAddress);
    bEmpty = ETH_IS_EMPTY(pcMacAddress);
    return !bBroadcast && !bEmpty && !bMulticast && (!bLocal || bLA);
}

static eInspectedPacketType QueryPacketType(PVOID data)
{
    if (ETH_IS_BROADCAST(data))
        return iptBroadcast;
    if (ETH_IS_MULTICAST(data))
        return iptMulticast;
    return iptUnicast;
}

typedef struct _tagConfigurationEntry
{
    const char      *Name;
    ULONG           ulValue;
    ULONG           ulMinimal;
    ULONG           ulMaximal;
}tConfigurationEntry;

typedef struct _tagConfigurationEntries
{
    tConfigurationEntry isPromiscuous;
    tConfigurationEntry PrioritySupport;
    tConfigurationEntry ConnectRate;
    tConfigurationEntry isLogEnabled;
    tConfigurationEntry debugLevel;
    tConfigurationEntry connectTimer;
    tConfigurationEntry dpcChecker;
    tConfigurationEntry TxCapacity;
    tConfigurationEntry RxCapacity;
    tConfigurationEntry InterruptRecovery;
    tConfigurationEntry LogStatistics;
    tConfigurationEntry PacketFiltering;
    tConfigurationEntry ScatterGather;
    tConfigurationEntry BatchReceive;
    tConfigurationEntry OffloadTxChecksum;
    tConfigurationEntry OffloadTxLSO;
    tConfigurationEntry OffloadRxCS;
    tConfigurationEntry OffloadGuestCS;
    tConfigurationEntry UseSwTxChecksum;
    tConfigurationEntry IPPacketsCheck;
    tConfigurationEntry stdIpcsV4;
    tConfigurationEntry stdTcpcsV4;
    tConfigurationEntry stdTcpcsV6;
    tConfigurationEntry stdUdpcsV4;
    tConfigurationEntry stdUdpcsV6;
    tConfigurationEntry stdLsoV1;
    tConfigurationEntry stdLsoV2ip4;
    tConfigurationEntry stdLsoV2ip6;
    tConfigurationEntry PriorityVlanTagging;
    tConfigurationEntry VlanId;
    tConfigurationEntry UseMergeableBuffers;
    tConfigurationEntry MTU;
    tConfigurationEntry NumberOfHandledRXPackersInDPC;
    tConfigurationEntry Indirect;
}tConfigurationEntries;

static const tConfigurationEntries defaultConfiguration =
{
    { "Promiscuous",    0,  0,  1 },
    { "Priority",       0,  0,  1 },
    { "ConnectRate",    100,10,10000 },
    { "DoLog",          1,  0,  1 },
    { "DebugLevel",     2,  0,  8 },
    { "ConnectTimer",   0,  0,  300000 },
    { "DpcCheck",       0,  0,  2 },
    { "TxCapacity",     1024,   16, 1024 },
    { "RxCapacity",     256, 32, 1024 },
    { "InterruptRecovery",  0, 0, 1},
    { "LogStatistics",  0, 0, 10000},
    { "PacketFilter",   1, 0, 1},
    { "Gather",         1, 0, 1},
    { "BatchReceive",   1, 0, 1},
    { "Offload.TxChecksum", 0, 0, 31},
    { "Offload.TxLSO",  0, 0, 2},
    { "Offload.RxCS",   0, 0, 31},
    { "Offload.GuestCS", 0, 0, 1},
    { "UseSwTxChecksum", 0, 0, 1 },
    { "IPPacketsCheck", 0, 0, 3 },
    { "*IPChecksumOffloadIPv4", 3, 0, 3 },
    { "*TCPChecksumOffloadIPv4",3, 0, 3 },
    { "*TCPChecksumOffloadIPv6",3, 0, 3 },
    { "*UDPChecksumOffloadIPv4",3, 0, 3 },
    { "*UDPChecksumOffloadIPv6",3, 0, 3 },
    { "*LsoV1IPv4", 1, 0, 1 },
    { "*LsoV2IPv4", 1, 0, 1 },
    { "*LsoV2IPv6", 1, 0, 1 },
    { "*PriorityVLANTag", 3, 0, 3},
    { "VlanId", 0, 0, MAX_VLAN_ID},
    { "MergeableBuf", 1, 0, 1},
    { "MTU", 1500, 500, 65500},
    { "NumberOfHandledRXPackersInDPC", MAX_RX_LOOPS, 1, 10000},
    { "Indirect", 0, 0, 2},
};

static void ParaNdis_ResetVirtIONetDevice(PARANDIS_ADAPTER *pContext)
{
    virtio_device_reset(&pContext->IODevice);
    DPrintf(0, ("[%s] Done", __FUNCTION__));
    /* reset all the features in the device */
    pContext->ulCurrentVlansFilterSet = 0;
    pContext->ullGuestFeatures = 0;
#ifdef VIRTIO_RESET_VERIFY
    if (1)
    {
        u8 devStatus;
        devStatus = virtio_get_status(&pContext->IODevice);
        if (devStatus)
        {
            DPrintf(0, ("[%s] Device status is still %02X", __FUNCTION__, (ULONG)devStatus));
            virtio_device_reset(&pContext->IODevice);
            devStatus = virtio_get_status(&pContext->IODevice);
            DPrintf(0, ("[%s] Device status on retry %02X", __FUNCTION__, (ULONG)devStatus));
        }
    }
#endif
}

/**********************************************************
Gets integer value for specifies in pEntry->Name name
Parameters:
    NDIS_HANDLE cfg  previously open configuration
    tConfigurationEntry *pEntry - Entry to fill value in
***********************************************************/
static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry)
{
    NDIS_STATUS status;
    const char *statusName;
    NDIS_STRING name = {0};
    PNDIS_CONFIGURATION_PARAMETER pParam = NULL;
    NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger;
    NdisInitializeString(&name, (PUCHAR)pEntry->Name);
    NdisReadConfiguration(
        &status,
        &pParam,
        cfg,
        &name,
        ParameterType);
    if (status == NDIS_STATUS_SUCCESS)
    {
        ULONG ulValue = pParam->ParameterData.IntegerData;
        if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal)
        {
            pEntry->ulValue = ulValue;
            statusName = "value";
        }
        else
        {
            statusName = "out of range";
        }
    }
    else
    {
        statusName = "nothing";
    }
    DPrintf(2, ("[%s] %s read for %s - 0x%x",
        __FUNCTION__,
        statusName,
        pEntry->Name,
        pEntry->ulValue));
    if (name.Buffer) NdisFreeString(name);
}

static void DisableLSOv4Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
    if (pContext->Offload.flagsValue & osbT4Lso)
    {
        DPrintf(0, ("[%s] Warning: %s", procname, reason));
        pContext->Offload.flagsValue &= ~osbT4Lso;
        ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
    }
}

static void DisableLSOv6Permanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
    if (pContext->Offload.flagsValue & osbT6Lso)
    {
        DPrintf(0, ("[%s] Warning: %s", procname, reason));
        pContext->Offload.flagsValue &= ~osbT6Lso;
        ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
    }
}

static void DisableBothLSOPermanently(PARANDIS_ADAPTER *pContext, LPCSTR procname, LPCSTR reason)
{
    if (pContext->Offload.flagsValue & (osbT4Lso | osbT6Lso))
    {
        DPrintf(0, ("[%s] Warning: %s", procname, reason));
        pContext->Offload.flagsValue &= ~(osbT6Lso | osbT4Lso);
        ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
    }
}

/**********************************************************
Loads NIC parameters from adapter registry key
Parameters:
    context
    PUCHAR *ppNewMACAddress - pointer to hold MAC address if configured from host
***********************************************************/
static void ReadNicConfiguration(PARANDIS_ADAPTER *pContext, PUCHAR *ppNewMACAddress)
{
    NDIS_HANDLE cfg;
    tConfigurationEntries *pConfiguration = ParaNdis_AllocateMemory(pContext, sizeof(tConfigurationEntries));
    if (pConfiguration)
    {
        *pConfiguration = defaultConfiguration;
        cfg = ParaNdis_OpenNICConfiguration(pContext);
        if (cfg)
        {
            GetConfigurationEntry(cfg, &pConfiguration->isLogEnabled);
            GetConfigurationEntry(cfg, &pConfiguration->debugLevel);
            GetConfigurationEntry(cfg, &pConfiguration->ConnectRate);
            GetConfigurationEntry(cfg, &pConfiguration->PrioritySupport);
            GetConfigurationEntry(cfg, &pConfiguration->isPromiscuous);
            GetConfigurationEntry(cfg, &pConfiguration->TxCapacity);
            GetConfigurationEntry(cfg, &pConfiguration->RxCapacity);
            GetConfigurationEntry(cfg, &pConfiguration->connectTimer);
            GetConfigurationEntry(cfg, &pConfiguration->dpcChecker);
            GetConfigurationEntry(cfg, &pConfiguration->InterruptRecovery);
            GetConfigurationEntry(cfg, &pConfiguration->LogStatistics);
            GetConfigurationEntry(cfg, &pConfiguration->PacketFiltering);
            GetConfigurationEntry(cfg, &pConfiguration->ScatterGather);
            GetConfigurationEntry(cfg, &pConfiguration->BatchReceive);
            GetConfigurationEntry(cfg, &pConfiguration->OffloadTxChecksum);
            GetConfigurationEntry(cfg, &pConfiguration->OffloadTxLSO);
            GetConfigurationEntry(cfg, &pConfiguration->OffloadRxCS);
            GetConfigurationEntry(cfg, &pConfiguration->OffloadGuestCS);
            GetConfigurationEntry(cfg, &pConfiguration->UseSwTxChecksum);
            GetConfigurationEntry(cfg, &pConfiguration->IPPacketsCheck);
            GetConfigurationEntry(cfg, &pConfiguration->stdIpcsV4);
            GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV4);
            GetConfigurationEntry(cfg, &pConfiguration->stdTcpcsV6);
            GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV4);
            GetConfigurationEntry(cfg, &pConfiguration->stdUdpcsV6);
            GetConfigurationEntry(cfg, &pConfiguration->stdLsoV1);
            GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip4);
            GetConfigurationEntry(cfg, &pConfiguration->stdLsoV2ip6);
            GetConfigurationEntry(cfg, &pConfiguration->PriorityVlanTagging);
            GetConfigurationEntry(cfg, &pConfiguration->VlanId);
            GetConfigurationEntry(cfg, &pConfiguration->UseMergeableBuffers);
            GetConfigurationEntry(cfg, &pConfiguration->MTU);
            GetConfigurationEntry(cfg, &pConfiguration->NumberOfHandledRXPackersInDPC);
            GetConfigurationEntry(cfg, &pConfiguration->Indirect);

    #if !defined(WPP_EVENT_TRACING)
            bDebugPrint = pConfiguration->isLogEnabled.ulValue;
            nDebugLevel = pConfiguration->debugLevel.ulValue;
    #endif
            // ignoring promiscuous setting, nothing to do with it
            pContext->maxFreeTxDescriptors = pConfiguration->TxCapacity.ulValue;
            pContext->NetMaxReceiveBuffers = pConfiguration->RxCapacity.ulValue;
            pContext->ulMilliesToConnect = pConfiguration->connectTimer.ulValue;
            pContext->nEnableDPCChecker = pConfiguration->dpcChecker.ulValue;
            pContext->bDoInterruptRecovery = pConfiguration->InterruptRecovery.ulValue != 0;
            pContext->Limits.nPrintDiagnostic = pConfiguration->LogStatistics.ulValue;
            pContext->uNumberOfHandledRXPacketsInDPC = pConfiguration->NumberOfHandledRXPackersInDPC.ulValue;
            pContext->bDoSupportPriority = pConfiguration->PrioritySupport.ulValue != 0;
            pContext->ulFormalLinkSpeed  = pConfiguration->ConnectRate.ulValue;
            pContext->ulFormalLinkSpeed *= 1000000;
            pContext->bDoHwPacketFiltering = pConfiguration->PacketFiltering.ulValue != 0;
            pContext->bUseScatterGather  = pConfiguration->ScatterGather.ulValue != 0;
            pContext->bBatchReceive      = pConfiguration->BatchReceive.ulValue != 0;
            pContext->bDoHardwareChecksum = pConfiguration->UseSwTxChecksum.ulValue == 0;
            pContext->bDoGuestChecksumOnReceive = pConfiguration->OffloadGuestCS.ulValue != 0;
            pContext->bDoIPCheckTx = pConfiguration->IPPacketsCheck.ulValue & 1;
            pContext->bDoIPCheckRx = pConfiguration->IPPacketsCheck.ulValue & 2;
            pContext->Offload.flagsValue = 0;
            // TX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
            if (pConfiguration->OffloadTxChecksum.ulValue & 1) pContext->Offload.flagsValue |= osbT4TcpChecksum | osbT4TcpOptionsChecksum;
            if (pConfiguration->OffloadTxChecksum.ulValue & 2) pContext->Offload.flagsValue |= osbT4UdpChecksum;
            if (pConfiguration->OffloadTxChecksum.ulValue & 4) pContext->Offload.flagsValue |= osbT4IpChecksum | osbT4IpOptionsChecksum;
            if (pConfiguration->OffloadTxChecksum.ulValue & 8) pContext->Offload.flagsValue |= osbT6TcpChecksum | osbT6TcpOptionsChecksum;
            if (pConfiguration->OffloadTxChecksum.ulValue & 16) pContext->Offload.flagsValue |= osbT6UdpChecksum;
            if (pConfiguration->OffloadTxLSO.ulValue) pContext->Offload.flagsValue |= osbT4Lso | osbT4LsoIp | osbT4LsoTcp;
            if (pConfiguration->OffloadTxLSO.ulValue > 1) pContext->Offload.flagsValue |= osbT6Lso | osbT6LsoTcpOptions;
            // RX caps: 1 - TCP, 2 - UDP, 4 - IP, 8 - TCPv6, 16 - UDPv6
            if (pConfiguration->OffloadRxCS.ulValue & 1) pContext->Offload.flagsValue |= osbT4RxTCPChecksum | osbT4RxTCPOptionsChecksum;
            if (pConfiguration->OffloadRxCS.ulValue & 2) pContext->Offload.flagsValue |= osbT4RxUDPChecksum;
            if (pConfiguration->OffloadRxCS.ulValue & 4) pContext->Offload.flagsValue |= osbT4RxIPChecksum | osbT4RxIPOptionsChecksum;
            if (pConfiguration->OffloadRxCS.ulValue & 8) pContext->Offload.flagsValue |= osbT6RxTCPChecksum | osbT6RxTCPOptionsChecksum;
            if (pConfiguration->OffloadRxCS.ulValue & 16) pContext->Offload.flagsValue |= osbT6RxUDPChecksum;
            /* full packet size that can be configured as GSO for VIRTIO is short */
            /* NDIS test fails sometimes fails on segments 50-60K */
            pContext->Offload.maxPacketSize = PARANDIS_MAX_LSO_SIZE;
            pContext->InitialOffloadParameters.IPv4Checksum = (UCHAR)pConfiguration->stdIpcsV4.ulValue;
            pContext->InitialOffloadParameters.TCPIPv4Checksum = (UCHAR)pConfiguration->stdTcpcsV4.ulValue;
            pContext->InitialOffloadParameters.TCPIPv6Checksum = (UCHAR)pConfiguration->stdTcpcsV6.ulValue;
            pContext->InitialOffloadParameters.UDPIPv4Checksum = (UCHAR)pConfiguration->stdUdpcsV4.ulValue;
            pContext->InitialOffloadParameters.UDPIPv6Checksum = (UCHAR)pConfiguration->stdUdpcsV6.ulValue;
            pContext->InitialOffloadParameters.LsoV1 = (UCHAR)pConfiguration->stdLsoV1.ulValue;
            pContext->InitialOffloadParameters.LsoV2IPv4 = (UCHAR)pConfiguration->stdLsoV2ip4.ulValue;
            pContext->InitialOffloadParameters.LsoV2IPv6 = (UCHAR)pConfiguration->stdLsoV2ip6.ulValue;
            pContext->ulPriorityVlanSetting = pConfiguration->PriorityVlanTagging.ulValue;
            pContext->VlanId = pConfiguration->VlanId.ulValue & 0xfff;
            pContext->bUseMergedBuffers = pConfiguration->UseMergeableBuffers.ulValue != 0;
            pContext->MaxPacketSize.nMaxDataSize = pConfiguration->MTU.ulValue;
            pContext->bUseIndirect = pConfiguration->Indirect.ulValue != 0;
            if (!pContext->bDoSupportPriority)
                pContext->ulPriorityVlanSetting = 0;
            // if Vlan not supported
            if (!IsVlanSupported(pContext))
                pContext->VlanId = 0;
            if (1)
            {
                NDIS_STATUS status;
                PVOID p;
                UINT  len = 0;
                NdisReadNetworkAddress(&status, &p, &len, cfg);
                if (status == NDIS_STATUS_SUCCESS && len == sizeof(pContext->CurrentMacAddress))
                {
                    *ppNewMACAddress = ParaNdis_AllocateMemory(pContext, sizeof(pContext->CurrentMacAddress));
                    if (*ppNewMACAddress)
                    {
                        NdisMoveMemory(*ppNewMACAddress, p, len);
                    }
                    else
                    {
                        DPrintf(0, ("[%s] MAC address present, but some problem also...", __FUNCTION__));
                    }
                }
                else if (len && len != sizeof(pContext->CurrentMacAddress))
                {
                    DPrintf(0, ("[%s] MAC address has wrong length of %d", __FUNCTION__, len));
                }
                else
                {
                    DPrintf(4, ("[%s] Nothing read for MAC, error %X", __FUNCTION__, status));
                }
            }
            NdisCloseConfiguration(cfg);
        }
        NdisFreeMemory(pConfiguration, 0, 0);
    }
}

void ParaNdis_ResetOffloadSettings(PARANDIS_ADAPTER *pContext, tOffloadSettingsFlags *pDest, PULONG from)
{
    if (!pDest) pDest = &pContext->Offload.flags;
    if (!from)  from = &pContext->Offload.flagsValue;

    pDest->fTxIPChecksum = !!(*from & osbT4IpChecksum);
    pDest->fTxTCPChecksum = !!(*from & osbT4TcpChecksum);
    pDest->fTxUDPChecksum = !!(*from & osbT4UdpChecksum);
    pDest->fTxTCPOptions = !!(*from & osbT4TcpOptionsChecksum);
    pDest->fTxIPOptions = !!(*from & osbT4IpOptionsChecksum);

    pDest->fTxLso = !!(*from & osbT4Lso);
    pDest->fTxLsoIP = !!(*from & osbT4LsoIp);
    pDest->fTxLsoTCP = !!(*from & osbT4LsoTcp);

    pDest->fRxIPChecksum = !!(*from & osbT4RxIPChecksum);
    pDest->fRxIPOptions = !!(*from & osbT4RxIPOptionsChecksum);
    pDest->fRxTCPChecksum = !!(*from & osbT4RxTCPChecksum);
    pDest->fRxTCPOptions = !!(*from & osbT4RxTCPOptionsChecksum);
    pDest->fRxUDPChecksum = !!(*from & osbT4RxUDPChecksum);

    pDest->fTxTCPv6Checksum = !!(*from & osbT6TcpChecksum);
    pDest->fTxTCPv6Options = !!(*from & osbT6TcpOptionsChecksum);
    pDest->fTxUDPv6Checksum = !!(*from & osbT6UdpChecksum);
    pDest->fTxIPv6Ext = !!(*from & osbT6IpExtChecksum);

    pDest->fTxLsov6 = !!(*from & osbT6Lso);
    pDest->fTxLsov6IP = !!(*from & osbT6LsoIpExt);
    pDest->fTxLsov6TCP = !!(*from & osbT6LsoTcpOptions);

    pDest->fRxTCPv6Checksum = !!(*from & osbT6RxTCPChecksum);
    pDest->fRxTCPv6Options = !!(*from & osbT6RxTCPOptionsChecksum);
    pDest->fRxUDPv6Checksum = !!(*from & osbT6RxUDPChecksum);
    pDest->fRxIPv6Ext = !!(*from & osbT6RxIpExtChecksum);
}

/**********************************************************
Enumerates adapter resources and fills the structure holding them
Verifies that IO assigned and has correct size
Verifies that interrupt assigned
Parameters:
    PNDIS_RESOURCE_LIST RList - list of resources, received from NDIS
    tAdapterResources *pResources - structure to fill
Return value:
    TRUE if everything is OK
***********************************************************/
static BOOLEAN GetAdapterResources(NDIS_HANDLE MiniportHandle, PNDIS_RESOURCE_LIST RList, tAdapterResources *pResources)
{
    UINT i;
    int read, bar = -1;
    PCI_COMMON_HEADER pci_config;
    NdisZeroMemory(pResources, sizeof(*pResources));

    // read the PCI config space header
    read = NdisReadPciSlotInformation(
       MiniportHandle,
       0 /* SlotNumber, reserved */,
       0 /* Offset */,
       &pci_config,
       sizeof(pci_config));
    if (read != sizeof(pci_config)) {
       return FALSE;
    }

    for (i = 0; i < RList->Count; ++i)
    {
        ULONG type = RList->PartialDescriptors[i].Type;
        if (type == CmResourceTypePort)
        {
            PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Port.Start;
            ULONG len = RList->PartialDescriptors[i].u.Port.Length;
            DPrintf(0, ("Found IO ports at %08lX(%d)", Start.LowPart, len));
            bar = virtio_get_bar_index(&pci_config, Start);
            if (bar < 0) {
               break;
            }
            pResources->PciBars[bar].BasePA = Start;
            pResources->PciBars[bar].uLength = len;
            pResources->PciBars[bar].bPortSpace = TRUE;
        }
        else if (type == CmResourceTypeMemory)
        {
            PHYSICAL_ADDRESS Start = RList->PartialDescriptors[i].u.Memory.Start;
            ULONG len = RList->PartialDescriptors[i].u.Memory.Length;
            DPrintf(0, ("Found IO memory at %08I64X(%d)", Start.QuadPart, len));
            bar = virtio_get_bar_index(&pci_config, Start);
            if (bar < 0) {
               break;
            }
            pResources->PciBars[bar].BasePA = Start;
            pResources->PciBars[bar].uLength = len;
            pResources->PciBars[bar].bPortSpace = FALSE;
        }
        else if (type == CmResourceTypeInterrupt)
        {
            pResources->Vector = RList->PartialDescriptors[i].u.Interrupt.Vector;
            pResources->Level = RList->PartialDescriptors[i].u.Interrupt.Level;
            pResources->Affinity = RList->PartialDescriptors[i].u.Interrupt.Affinity;
            pResources->InterruptFlags = RList->PartialDescriptors[i].Flags;
            DPrintf(0, ("Found Interrupt vector %d, level %d, affinity %X, flags %X",
                pResources->Vector, pResources->Level, (ULONG)pResources->Affinity, pResources->InterruptFlags));
        }
    }
    return bar >= 0 && pResources->Vector;
}

static void DumpVirtIOFeatures(PARANDIS_ADAPTER *pContext)
{
    const struct {  ULONG bitmask;  const PCHAR Name; } Features[] =
    {

        {VIRTIO_NET_F_CSUM, "VIRTIO_NET_F_CSUM" },
        {VIRTIO_NET_F_GUEST_CSUM, "VIRTIO_NET_F_GUEST_CSUM" },
        {VIRTIO_NET_F_MAC, "VIRTIO_NET_F_MAC" },
        {VIRTIO_NET_F_GSO, "VIRTIO_NET_F_GSO" },
        {VIRTIO_NET_F_GUEST_TSO4, "VIRTIO_NET_F_GUEST_TSO4"},
        {VIRTIO_NET_F_GUEST_TSO6, "VIRTIO_NET_F_GUEST_TSO6"},
        {VIRTIO_NET_F_GUEST_ECN, "VIRTIO_NET_F_GUEST_ECN"},
        {VIRTIO_NET_F_GUEST_UFO, "VIRTIO_NET_F_GUEST_UFO"},
        {VIRTIO_NET_F_HOST_TSO4, "VIRTIO_NET_F_HOST_TSO4"},
        {VIRTIO_NET_F_HOST_TSO6, "VIRTIO_NET_F_HOST_TSO6"},
        {VIRTIO_NET_F_HOST_ECN, "VIRTIO_NET_F_HOST_ECN"},
        {VIRTIO_NET_F_HOST_UFO, "VIRTIO_NET_F_HOST_UFO"},
        {VIRTIO_NET_F_MRG_RXBUF, "VIRTIO_NET_F_MRG_RXBUF"},
        {VIRTIO_NET_F_STATUS, "VIRTIO_NET_F_STATUS"},
        {VIRTIO_NET_F_CTRL_VQ, "VIRTIO_NET_F_CTRL_VQ"},
        {VIRTIO_NET_F_CTRL_RX, "VIRTIO_NET_F_CTRL_RX"},
        {VIRTIO_NET_F_CTRL_VLAN, "VIRTIO_NET_F_CTRL_VLAN"},
        {VIRTIO_NET_F_CTRL_RX_EXTRA, "VIRTIO_NET_F_CTRL_RX_EXTRA"},
        {VIRTIO_RING_F_INDIRECT_DESC, "VIRTIO_RING_F_INDIRECT_DESC"},
        {VIRTIO_F_VERSION_1, "VIRTIO_F_VERSION_1" },
        {VIRTIO_F_ANY_LAYOUT, "VIRTIO_F_ANY_LAYOUT" },
    };
    UINT i;
    for (i = 0; i < sizeof(Features)/sizeof(Features[0]); ++i)
    {
        if (VirtIODeviceGetHostFeature(pContext, Features[i].bitmask))
        {
            DPrintf(0, ("VirtIO Host Feature %s", Features[i].Name));
        }
    }
}

/**********************************************************
    Only for test. Prints out if the interrupt line is ON
Parameters:
Return value:
***********************************************************/
static void JustForCheckClearInterrupt(PARANDIS_ADAPTER *pContext, const char *Label)
{
    if (pContext->bEnableInterruptChecking)
    {
        ULONG ulActive;
        ulActive = virtio_read_isr_status(&pContext->IODevice);
        if (ulActive)
        {
            DPrintf(0,("WARNING: Interrupt Line %d(%s)!", ulActive, Label));
        }
    }
}

/**********************************************************
Prints out statistics
***********************************************************/
static void PrintStatistics(PARANDIS_ADAPTER *pContext)
{
    ULONG64 totalTxFrames =
        pContext->Statistics.ifHCOutBroadcastPkts +
        pContext->Statistics.ifHCOutMulticastPkts +
        pContext->Statistics.ifHCOutUcastPkts;
    ULONG64 totalRxFrames =
        pContext->Statistics.ifHCInBroadcastPkts +
        pContext->Statistics.ifHCInMulticastPkts +
        pContext->Statistics.ifHCInUcastPkts;

    DPrintf(0, ("[Diag!%X] RX buffers at VIRTIO %d of %d",
        pContext->CurrentMacAddress[5],
        pContext->NetNofReceiveBuffers,
        pContext->NetMaxReceiveBuffers));
    DPrintf(0, ("[Diag!] TX desc available %d/%d, buf %d/min. %d",
        pContext->nofFreeTxDescriptors,
        pContext->maxFreeTxDescriptors,
        pContext->nofFreeHardwareBuffers,
        pContext->minFreeHardwareBuffers));
    pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers;
    if (pContext->NetTxPacketsToReturn)
    {
        DPrintf(0, ("[Diag!] TX packets to return %d", pContext->NetTxPacketsToReturn));
    }
    DPrintf(0, ("[Diag!] Bytes transmitted %I64u, received %I64u",
        pContext->Statistics.ifHCOutOctets,
        pContext->Statistics.ifHCInOctets));
    DPrintf(0, ("[Diag!] Tx frames %I64u, CSO %d, LSO %d, indirect %d",
        totalTxFrames,
        pContext->extraStatistics.framesCSOffload,
        pContext->extraStatistics.framesLSO,
        pContext->extraStatistics.framesIndirect));
    DPrintf(0, ("[Diag!] Rx frames %I64u, Rx.Pri %d, RxHwCS.OK %d, FiltOut %d",
        totalRxFrames, pContext->extraStatistics.framesRxPriority,
        pContext->extraStatistics.framesRxCSHwOK, pContext->extraStatistics.framesFilteredOut));
    if (pContext->extraStatistics.framesRxCSHwMissedBad || pContext->extraStatistics.framesRxCSHwMissedGood)
    {
        DPrintf(0, ("[Diag!] RxHwCS mistakes: missed bad %d, missed good %d",
            pContext->extraStatistics.framesRxCSHwMissedBad, pContext->extraStatistics.framesRxCSHwMissedGood));
    }
}

static NDIS_STATUS NTStatusToNdisStatus(NTSTATUS nt_status) {
    switch (nt_status) {
    case STATUS_SUCCESS:
        return NDIS_STATUS_SUCCESS;
    case STATUS_NOT_FOUND:
    case STATUS_DEVICE_NOT_CONNECTED:
        return NDIS_STATUS_ADAPTER_NOT_FOUND;
    case STATUS_INSUFFICIENT_RESOURCES:
        return NDIS_STATUS_RESOURCES;
    case STATUS_INVALID_PARAMETER:
        return NDIS_STATUS_INVALID_DEVICE_REQUEST;
    default:
        return NDIS_STATUS_FAILURE;
    }
}

static NDIS_STATUS FinalizeFeatures(PARANDIS_ADAPTER *pContext)
{
    NTSTATUS nt_status = virtio_set_features(&pContext->IODevice, pContext->ullGuestFeatures);
    if (!NT_SUCCESS(nt_status)) {
        DPrintf(0, ("[%s] virtio_set_features failed with %x\n", __FUNCTION__, nt_status));
    }
    return NTStatusToNdisStatus(nt_status);
}

/**********************************************************
Initializes the context structure
Major variables, received from NDIS on initialization, must be be set before this call
(for ex. pContext->MiniportHandle)

If this procedure fails, no need to call
    ParaNdis_CleanupContext


Parameters:
Return value:
    SUCCESS, if resources are OK
    NDIS_STATUS_RESOURCE_CONFLICT if not
***********************************************************/
NDIS_STATUS ParaNdis_InitializeContext(
    PARANDIS_ADAPTER *pContext,
    PNDIS_RESOURCE_LIST pResourceList)
{
    NDIS_STATUS status = NDIS_STATUS_SUCCESS;
    PUCHAR pNewMacAddress = NULL;
    USHORT linkStatus = 0;
    NTSTATUS nt_status;

    DEBUG_ENTRY(0);
    /* read first PCI IO bar*/
    //ulIOAddress = ReadPCIConfiguration(miniportAdapterHandle, 0x10);
    /* check this is IO and assigned */
    ReadNicConfiguration(pContext, &pNewMacAddress);
    if (pNewMacAddress)
    {
        if (ParaNdis_ValidateMacAddress(pNewMacAddress, TRUE))
        {
            DPrintf(0, ("[%s] WARNING: MAC address reloaded", __FUNCTION__));
            NdisMoveMemory(pContext->CurrentMacAddress, pNewMacAddress, sizeof(pContext->CurrentMacAddress));
        }
        else
        {
            DPrintf(0, ("[%s] WARNING: Invalid MAC address ignored", __FUNCTION__));
        }
        NdisFreeMemory(pNewMacAddress, 0, 0);
    }

    pContext->MaxPacketSize.nMaxFullSizeOS = pContext->MaxPacketSize.nMaxDataSize + ETH_HEADER_SIZE;
    pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeOS;
    pContext->MaxPacketSize.nMaxFullSizeHwRx = pContext->MaxPacketSize.nMaxFullSizeOS + ETH_PRIORITY_HEADER_SIZE;
    if (pContext->ulPriorityVlanSetting)
        pContext->MaxPacketSize.nMaxFullSizeHwTx = pContext->MaxPacketSize.nMaxFullSizeHwRx;

    if (GetAdapterResources(pContext->MiniportHandle, pResourceList, &pContext->AdapterResources))
    {
        if (pContext->AdapterResources.InterruptFlags & CM_RESOURCE_INTERRUPT_MESSAGE)
        {
            DPrintf(0, ("[%s] Message interrupt assigned", __FUNCTION__));
            pContext->bUsingMSIX = TRUE;
        }

        nt_status = virtio_device_initialize(
            &pContext->IODevice,
            &ParaNdisSystemOps,
            pContext,
            pContext->bUsingMSIX);
        if (!NT_SUCCESS(nt_status)) {
            DPrintf(0, ("[%s] virtio_device_initialize failed with %x\n", __FUNCTION__, nt_status));
            status = NTStatusToNdisStatus(nt_status);
            DEBUG_EXIT_STATUS(0, status);
            return status;
        }

        pContext->bIODeviceInitialized = TRUE;
        JustForCheckClearInterrupt(pContext, "init 0");
        ParaNdis_ResetVirtIONetDevice(pContext);
        JustForCheckClearInterrupt(pContext, "init 1");
        virtio_add_status(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE);
        JustForCheckClearInterrupt(pContext, "init 2");
        virtio_add_status(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER);
        pContext->ullHostFeatures = virtio_get_features(&pContext->IODevice);
        DumpVirtIOFeatures(pContext);
        JustForCheckClearInterrupt(pContext, "init 3");
        pContext->bLinkDetectSupported = 0 != VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_STATUS);

        if(pContext->bLinkDetectSupported) {
            virtio_get_config(&pContext->IODevice, sizeof(pContext->CurrentMacAddress), &linkStatus, sizeof(linkStatus));
            pContext->bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0;
            DPrintf(0, ("[%s] Link status on driver startup: %d", __FUNCTION__, pContext->bConnected));
        }

        if (VirtIODeviceGetHostFeature(pContext, VIRTIO_F_VERSION_1))
        {
            // virtio 1.0 always uses the extended header
            pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_ext);
            VirtIODeviceEnableGuestFeature(pContext, VIRTIO_F_VERSION_1);
        }
        else
        {
            pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_basic);
        }

        if (VirtIODeviceGetHostFeature(pContext, VIRTIO_F_ANY_LAYOUT))
        {
            VirtIODeviceEnableGuestFeature(pContext, VIRTIO_F_ANY_LAYOUT);
        }
        if (VirtIODeviceGetHostFeature(pContext, VIRTIO_RING_F_EVENT_IDX))
        {
            VirtIODeviceEnableGuestFeature(pContext, VIRTIO_RING_F_EVENT_IDX);
        }

        if (!pContext->bUseMergedBuffers && VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_MRG_RXBUF))
        {
            DPrintf(0, ("[%s] Not using mergeable buffers", __FUNCTION__));
        }
        else
        {
            pContext->bUseMergedBuffers = VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_MRG_RXBUF) != 0;
            if (pContext->bUseMergedBuffers)
            {
                pContext->nVirtioHeaderSize = sizeof(virtio_net_hdr_ext);
                VirtIODeviceEnableGuestFeature(pContext, VIRTIO_NET_F_MRG_RXBUF);
            }
        }
        if (VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_MAC))
        {
            virtio_get_config(
                &pContext->IODevice,
                0, // + offsetof(struct virtio_net_config, mac)
                &pContext->PermanentMacAddress,
                ETH_LENGTH_OF_ADDRESS);
            if (!ParaNdis_ValidateMacAddress(pContext->PermanentMacAddress, FALSE))
            {
                DPrintf(0,("Invalid device MAC ignored(%02x-%02x-%02x-%02x-%02x-%02x)",
                    pContext->PermanentMacAddress[0],
                    pContext->PermanentMacAddress[1],
                    pContext->PermanentMacAddress[2],
                    pContext->PermanentMacAddress[3],
                    pContext->PermanentMacAddress[4],
                    pContext->PermanentMacAddress[5]));
                NdisZeroMemory(pContext->PermanentMacAddress, sizeof(pContext->PermanentMacAddress));
            }
        }

        if (ETH_IS_EMPTY(pContext->PermanentMacAddress))
        {
            DPrintf(0, ("No device MAC present, use default"));
            pContext->PermanentMacAddress[0] = 0x02;
            pContext->PermanentMacAddress[1] = 0x50;
            pContext->PermanentMacAddress[2] = 0xF2;
            pContext->PermanentMacAddress[3] = 0x00;
            pContext->PermanentMacAddress[4] = 0x01;
            pContext->PermanentMacAddress[5] = 0x80 | (UCHAR)(pContext->ulUniqueID & 0xFF);
        }
        DPrintf(0,("Device MAC = %02x-%02x-%02x-%02x-%02x-%02x",
            pContext->PermanentMacAddress[0],
            pContext->PermanentMacAddress[1],
            pContext->PermanentMacAddress[2],
            pContext->PermanentMacAddress[3],
            pContext->PermanentMacAddress[4],
            pContext->PermanentMacAddress[5]));

        if (ETH_IS_EMPTY(pContext->CurrentMacAddress))
        {
            NdisMoveMemory(
                &pContext->CurrentMacAddress,
                &pContext->PermanentMacAddress,
                ETH_LENGTH_OF_ADDRESS);
        }
        else
        {
            DPrintf(0,("Current MAC = %02x-%02x-%02x-%02x-%02x-%02x",
                pContext->CurrentMacAddress[0],
                pContext->CurrentMacAddress[1],
                pContext->CurrentMacAddress[2],
                pContext->CurrentMacAddress[3],
                pContext->CurrentMacAddress[4],
                pContext->CurrentMacAddress[5]));
        }
        if (VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_CTRL_VQ)) {
            pContext->bHasControlQueue = TRUE;
            VirtIODeviceEnableGuestFeature(pContext, VIRTIO_NET_F_CTRL_VQ);
        }
    }
    else
    {
        DPrintf(0, ("[%s] Error: Incomplete resources", __FUNCTION__));
        status = NDIS_STATUS_RESOURCE_CONFLICT;<--- status is assigned
    }


    if (pContext->bDoHardwareChecksum)
    {
        ULONG dependentOptions;
        dependentOptions = osbT4TcpChecksum | osbT4UdpChecksum | osbT4TcpOptionsChecksum;
        if (!VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_CSUM) &&
            (pContext->Offload.flagsValue & dependentOptions))
        {
            DPrintf(0, ("[%s] Host does not support CSUM, disabling CS offload", __FUNCTION__) );
            pContext->Offload.flagsValue &= ~dependentOptions;
        }
    }

    if (pContext->bDoGuestChecksumOnReceive && VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_GUEST_CSUM))
    {
        DPrintf(0, ("[%s] Enabling guest checksum", __FUNCTION__) );
        VirtIODeviceEnableGuestFeature(pContext, VIRTIO_NET_F_GUEST_CSUM);
    }
    else
    {
        pContext->bDoGuestChecksumOnReceive = FALSE;
    }

    // now, after we checked the capabilities, we can initialize current
    // configuration of offload tasks
    ParaNdis_ResetOffloadSettings(pContext, NULL, NULL);
    if (pContext->Offload.flags.fTxLso && !pContext->bUseScatterGather)
    {
        DisableBothLSOPermanently(pContext, __FUNCTION__, "SG is not active");
    }
    if (pContext->Offload.flags.fTxLso &&
        !VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_HOST_TSO4))
    {
        DisableLSOv4Permanently(pContext, __FUNCTION__, "Host does not support TSOv4");
    }
    if (pContext->Offload.flags.fTxLsov6 &&
        !VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_HOST_TSO6))
    {
        DisableLSOv6Permanently(pContext, __FUNCTION__, "Host does not support TSOv6");
    }
    if (pContext->bUseIndirect)
    {
        const char *reason = "";
        if (!VirtIODeviceGetHostFeature(pContext, VIRTIO_RING_F_INDIRECT_DESC))
        {
            pContext->bUseIndirect = FALSE;
            reason = "Host support";
        }
        else if (!pContext->bUseScatterGather)
        {
            pContext->bUseIndirect = FALSE;
            reason = "SG";
        }
        DPrintf(0, ("[%s] %sable indirect Tx(!%s)", __FUNCTION__, pContext->bUseIndirect ? "En" : "Dis", reason) );
    }

    if (VirtIODeviceGetHostFeature(pContext, VIRTIO_NET_F_CTRL_RX_EXTRA) &&
        pContext->bDoHwPacketFiltering)
    {
        DPrintf(0, ("[%s] Using hardware packet filtering", __FUNCTION__));
        pContext->bHasHardwareFilters = TRUE;
    }

    status = FinalizeFeatures(pContext);<--- status is overwritten

    pContext->ReuseBufferProc = (tReuseReceiveBufferProc)ReuseReceiveBufferRegular;
    
    NdisInitializeEvent(&pContext->ResetEvent);
    DEBUG_EXIT_STATUS(0, status);
    return status;
}

/**********************************************************
Free the resources allocated for VirtIO buffer descriptor
Parameters:
    PVOID pParam                pIONetDescriptor to free
    BOOLEAN bRemoveFromList     TRUE, if also remove it from list
***********************************************************/
static void VirtIONetFreeBufferDescriptor(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBufferDescriptor)
{
    if(pBufferDescriptor)
    {
        if (pBufferDescriptor->pHolder)
            ParaNdis_UnbindBufferFromPacket(pContext, pBufferDescriptor);
        if (pBufferDescriptor->DataInfo.Virtual)
            ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->DataInfo);
        if (pBufferDescriptor->HeaderInfo.Virtual)
            ParaNdis_FreePhysicalMemory(pContext, &pBufferDescriptor->HeaderInfo);
        NdisFreeMemory(pBufferDescriptor, 0, 0);
    }
}

/**********************************************************
Free all the buffer descriptors from specified list
Parameters:
    PLIST_ENTRY pListRoot           list containing pIONetDescriptor structures
    PNDIS_SPIN_LOCK pLock           lock to protest this list
Return value:
***********************************************************/
static void FreeDescriptorsFromList(PARANDIS_ADAPTER *pContext, PLIST_ENTRY pListRoot, PNDIS_SPIN_LOCK pLock)
{
    pIONetDescriptor pBufferDescriptor;
    LIST_ENTRY TempList;
    InitializeListHead(&TempList);
    NdisAcquireSpinLock(pLock);
    while(!IsListEmpty(pListRoot))
    {
        pBufferDescriptor = (pIONetDescriptor)RemoveHeadList(pListRoot);
        InsertTailList(&TempList, &pBufferDescriptor->listEntry);
    }
    NdisReleaseSpinLock(pLock);
    while(!IsListEmpty(&TempList))
    {
        pBufferDescriptor = (pIONetDescriptor)RemoveHeadList(&TempList);
        VirtIONetFreeBufferDescriptor(pContext, pBufferDescriptor);
    }
}

static pIONetDescriptor AllocatePairOfBuffersOnInit(
    PARANDIS_ADAPTER *pContext,
    ULONG size1,
    ULONG size2,
    BOOLEAN bForTx)
{
    pIONetDescriptor p;
    p = (pIONetDescriptor)ParaNdis_AllocateMemory(pContext, sizeof(*p));
    if (p)
    {
        BOOLEAN b1 = FALSE, b2 = FALSE;
        NdisZeroMemory(p, sizeof(*p));
        p->HeaderInfo.size = size1;
        p->DataInfo.size   = size2;
        p->HeaderInfo.IsCached = p->DataInfo.IsCached = 1;
        p->HeaderInfo.IsTX = p->DataInfo.IsTX = bForTx;
        p->nofUsedBuffers = 0;
        b1 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->HeaderInfo);
        if (b1) b2 = ParaNdis_InitialAllocatePhysicalMemory(pContext, &p->DataInfo);
        if (b1 && b2)
        {
            BOOLEAN b = bForTx || ParaNdis_BindBufferToPacket(pContext, p);
            if (!b)
            {
                DPrintf(0, ("[INITPHYS](%s) Failed to bind memory to net packet", bForTx ? "TX" : "RX"));
                VirtIONetFreeBufferDescriptor(pContext, p);
                p = NULL;
            }
        }
        else
        {
            if (b1) ParaNdis_FreePhysicalMemory(pContext, &p->HeaderInfo);
            if (b2) ParaNdis_FreePhysicalMemory(pContext, &p->DataInfo);
            NdisFreeMemory(p, 0, 0);
            p = NULL;
            DPrintf(0, ("[INITPHYS](%s) Failed to allocate memory block", bForTx ? "TX" : "RX"));
        }
    }
    if (p)
    {
        DPrintf(3, ("[INITPHYS](%s) Header v%p(p%08lX), Data v%p(p%08lX)", bForTx ? "TX" : "RX",
            p->HeaderInfo.Virtual, p->HeaderInfo.Physical.LowPart,
            p->DataInfo.Virtual, p->DataInfo.Physical.LowPart));
    }
    return p;
}

/**********************************************************
Allocates TX buffers according to startup setting (pContext->maxFreeTxDescriptors as got from registry)
Buffers are chained in NetFreeSendBuffers
Parameters:
    context
***********************************************************/
static void PrepareTransmitBuffers(PARANDIS_ADAPTER *pContext)
{
    UINT nBuffers, nMaxBuffers;
    DEBUG_ENTRY(4);
    nMaxBuffers = virtio_get_queue_size(pContext->NetSendQueue) / 2;
    if (nMaxBuffers > pContext->maxFreeTxDescriptors) nMaxBuffers = pContext->maxFreeTxDescriptors;

    for (nBuffers = 0; nBuffers < nMaxBuffers; ++nBuffers)
    {
        pIONetDescriptor pBuffersDescriptor =
            AllocatePairOfBuffersOnInit(
                pContext,
                pContext->nVirtioHeaderSize,
                pContext->MaxPacketSize.nMaxFullSizeHwTx,
                TRUE);
        if (!pBuffersDescriptor) break;

        NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size);
        InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry);
        pContext->nofFreeTxDescriptors++;
    }

    pContext->maxFreeTxDescriptors = pContext->nofFreeTxDescriptors;
    pContext->nofFreeHardwareBuffers = pContext->nofFreeTxDescriptors * 2;
    pContext->maxFreeHardwareBuffers = pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers;
    DPrintf(0, ("[%s] available %d Tx descriptors, %d hw buffers",
        __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers));
}

static BOOLEAN AddRxBufferToQueue(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBufferDescriptor)
{
    UINT nBuffersToSubmit = 2;
    struct VirtIOBufferDescriptor sg[2];
    if (!pContext->bUseMergedBuffers)
    {
        sg[0].physAddr = pBufferDescriptor->HeaderInfo.Physical;
        sg[0].length = pBufferDescriptor->HeaderInfo.size;
        sg[1].physAddr = pBufferDescriptor->DataInfo.Physical;
        sg[1].length = pBufferDescriptor->DataInfo.size;
    }
    else
    {
        sg[0].physAddr = pBufferDescriptor->DataInfo.Physical;
        sg[0].length = pBufferDescriptor->DataInfo.size;
        nBuffersToSubmit = 1;
    }
    return 0 <= virtqueue_add_buf(
        pContext->NetReceiveQueue,
        sg,
        0,
        nBuffersToSubmit,
        pBufferDescriptor,
        NULL,
        0);
}


/**********************************************************
Allocates maximum RX buffers for incoming packets
Buffers are chained in NetReceiveBuffers
Parameters:
    context
***********************************************************/
static int PrepareReceiveBuffers(PARANDIS_ADAPTER *pContext)
{
    int nRet = 0;
    UINT i;
    DEBUG_ENTRY(4);

    for (i = 0; i < pContext->NetMaxReceiveBuffers; ++i)
    {
        ULONG size1 = pContext->bUseMergedBuffers ? 4 : pContext->nVirtioHeaderSize;
        ULONG size2 = pContext->MaxPacketSize.nMaxFullSizeHwRx +
            (pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0);
        pIONetDescriptor pBuffersDescriptor =
            AllocatePairOfBuffersOnInit(pContext, size1, size2, FALSE);
        if (!pBuffersDescriptor) break;

        if (!AddRxBufferToQueue(pContext, pBuffersDescriptor))
        {
            VirtIONetFreeBufferDescriptor(pContext, pBuffersDescriptor);
            break;
        }

        InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry);

        pContext->NetNofReceiveBuffers++;
    }

    pContext->NetMaxReceiveBuffers = pContext->NetNofReceiveBuffers;
    DPrintf(0, ("[%s] MaxReceiveBuffers %d\n", __FUNCTION__, pContext->NetMaxReceiveBuffers) );

    virtqueue_kick(pContext->NetReceiveQueue);

    return nRet;
}

static NDIS_STATUS FindNetQueues(PARANDIS_ADAPTER *pContext)
{
    struct virtqueue *queues[3];
    unsigned nvqs = pContext->bHasControlQueue ? 3 : 2;
    NTSTATUS status;

    // We work with two or three virtqueues, 0 - receive, 1 - send, 2 - control
    status = virtio_find_queues(
       &pContext->IODevice,
       nvqs,
       queues);
    if (!NT_SUCCESS(status)) {
       DPrintf(0, ("[%s] virtio_find_queues failed with %x\n", __FUNCTION__, status));
       return NTStatusToNdisStatus(status);
    }

    pContext->NetReceiveQueue = queues[0];
    pContext->NetSendQueue = queues[1];
    if (pContext->bHasControlQueue) {
       pContext->NetControlQueue = queues[2];
    }

    return NDIS_STATUS_SUCCESS;
}

// called on PASSIVE upon unsuccessful Init or upon Halt
static void DeleteNetQueues(PARANDIS_ADAPTER *pContext)
{
    virtio_delete_queues(&pContext->IODevice);
}

/**********************************************************
Initializes VirtIO buffering and related stuff:
Allocates RX and TX queues and buffers
Parameters:
    context
Return value:
    TRUE if both queues are allocated
***********************************************************/
static NDIS_STATUS ParaNdis_VirtIONetInit(PARANDIS_ADAPTER *pContext)
{
    NDIS_STATUS status;
    DEBUG_ENTRY(0);

    pContext->ControlData.IsCached = 1;
    pContext->ControlData.size = 512;

    status = FindNetQueues(pContext);
    if (status != NDIS_STATUS_SUCCESS) {
        return status;
    }

    if (pContext->NetReceiveQueue && pContext->NetSendQueue)
    {
        PrepareTransmitBuffers(pContext);
        PrepareReceiveBuffers(pContext);

        if (pContext->NetControlQueue)
            ParaNdis_InitialAllocatePhysicalMemory(pContext, &pContext->ControlData);
        if (!pContext->NetControlQueue || !pContext->ControlData.Virtual)
        {
            DPrintf(0, ("[%s] The Control vQueue does not work!\n", __FUNCTION__) );
            pContext->bHasHardwareFilters = FALSE;
        }
        if (pContext->nofFreeTxDescriptors &&
            pContext->NetMaxReceiveBuffers &&
            pContext->maxFreeHardwareBuffers)
        {
            pContext->sgTxGatherTable = ParaNdis_AllocateMemory(pContext,
                pContext->maxFreeHardwareBuffers * sizeof(pContext->sgTxGatherTable[0]));
            if (!pContext->sgTxGatherTable)
            {
                DisableBothLSOPermanently(pContext, __FUNCTION__, "Can not allocate SG table");
            }
            status = NDIS_STATUS_SUCCESS;
        }
    }
    else
    {
        DeleteNetQueues(pContext);
        status = NDIS_STATUS_RESOURCES;
    }
    return status;
}

static void VirtIODeviceRemoveStatus(VirtIODevice *vdev, u8 status)
{
    virtio_set_status(
        vdev,
        virtio_get_status(vdev) & ~status);
}

/**********************************************************
Finishes initialization of context structure, calling also version dependent part
If this procedure failed, ParaNdis_CleanupContext must be called
Parameters:
    context
Return value:
    SUCCESS or some kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_FinishInitialization(PARANDIS_ADAPTER *pContext)
{
    NDIS_STATUS status = NDIS_STATUS_SUCCESS;
    DEBUG_ENTRY(0);

    NdisAllocateSpinLock(&pContext->SendLock);
#if !defined(UNIFY_LOCKS)
    NdisAllocateSpinLock(&pContext->ReceiveLock);
#endif

    InitializeListHead(&pContext->NetReceiveBuffers);
    InitializeListHead(&pContext->NetReceiveBuffersWaiting);
    InitializeListHead(&pContext->NetSendBuffersInUse);
    InitializeListHead(&pContext->NetFreeSendBuffers);

    status = ParaNdis_FinishSpecificInitialization(pContext);

    if (status == NDIS_STATUS_SUCCESS)
    {
        status = ParaNdis_VirtIONetInit(pContext);
    }

    pContext->Limits.nReusedRxBuffers = pContext->NetMaxReceiveBuffers / 4 + 1;

    if (status == NDIS_STATUS_SUCCESS)
    {
        JustForCheckClearInterrupt(pContext, "start 3");
        pContext->bEnableInterruptHandlingDPC = TRUE;
        ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
        virtio_device_ready(&pContext->IODevice);
        JustForCheckClearInterrupt(pContext, "start 4");
        ParaNdis_UpdateDeviceFilters(pContext);
    }
    else
    {
        virtio_add_status(&pContext->IODevice, VIRTIO_CONFIG_S_FAILED);
    }
    DEBUG_EXIT_STATUS(0, status);
    return status;
}

/**********************************************************
Releases VirtIO related resources - queues and buffers
Parameters:
    context
Return value:
***********************************************************/
static void VirtIONetRelease(PARANDIS_ADAPTER *pContext)
{
    BOOLEAN b;
    DEBUG_ENTRY(0);

    /* list NetReceiveBuffersWaiting must be free */
    do
    {
        NdisAcquireSpinLock(&pContext->ReceiveLock);
        b = !IsListEmpty(&pContext->NetReceiveBuffersWaiting);
        NdisReleaseSpinLock(&pContext->ReceiveLock);
        if (b)
        {
            DPrintf(0, ("[%s] There are waiting buffers", __FUNCTION__));
            PrintStatistics(pContext);
            NdisMSleep(5000000);
        }
    }while (b);

    DeleteNetQueues(pContext);
    virtio_device_shutdown(&pContext->IODevice);
    pContext->bIODeviceInitialized = FALSE;

    /* intentionally commented out
    FreeDescriptorsFromList(
        pContext,
        &pContext->NetReceiveBuffersWaiting,
        &pContext->ReceiveLock);
    */

    /* this can be freed, queue shut down */
    FreeDescriptorsFromList(
        pContext,
        &pContext->NetReceiveBuffers,
        &pContext->ReceiveLock);

    /* this can be freed, queue shut down */
    FreeDescriptorsFromList(
        pContext,
        &pContext->NetSendBuffersInUse,
        &pContext->SendLock);

    /* this can be freed, send disabled */
    FreeDescriptorsFromList(
        pContext,
        &pContext->NetFreeSendBuffers,
        &pContext->SendLock);

    if (pContext->ControlData.Virtual)
        ParaNdis_FreePhysicalMemory(pContext, &pContext->ControlData);

    PrintStatistics(pContext);
    if (pContext->sgTxGatherTable)
    {
        NdisFreeMemory(pContext->sgTxGatherTable, 0, 0);
    }
}

static void PreventDPCServicing(PARANDIS_ADAPTER *pContext)
{
    LONG inside;;
    pContext->bEnableInterruptHandlingDPC = FALSE;
    do
    {
        inside = InterlockedIncrement(&pContext->counterDPCInside);
        InterlockedDecrement(&pContext->counterDPCInside);
        if (inside > 1)
        {
            DPrintf(0, ("[%s] waiting!", __FUNCTION__));
            NdisMSleep(20000);
        }
    } while (inside > 1);
}

/**********************************************************
Frees all the resources allocated when the context initialized,
    calling also version-dependent part
Parameters:
    context
***********************************************************/
VOID ParaNdis_CleanupContext(PARANDIS_ADAPTER *pContext)
{
    UINT i;

    /* disable any interrupt generation */
    if (pContext->IODevice.addr)
    {
        //int nActive;
        //nActive = virtio_read_isr_status(&pContext->IODevice);
        /* back compat - remove the OK flag only in legacy mode */
        VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
        JustForCheckClearInterrupt(pContext, "exit 1");
        //nActive += virtio_read_isr_status(&pContext->IODevice);
        //nActive += virtio_read_isr_status(&pContext->IODevice);
        //DPrintf(0, ("cleanup %d", nActive));
    }

    PreventDPCServicing(pContext);

    /****************************************
    ensure all the incoming packets returned,
    free all the buffers and their descriptors
    *****************************************/

    if (pContext->bIODeviceInitialized)
    {
        JustForCheckClearInterrupt(pContext, "exit 2");
        ParaNdis_ResetVirtIONetDevice(pContext);
        JustForCheckClearInterrupt(pContext, "exit 3");
    }

    ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);
    VirtIONetRelease(pContext);

    ParaNdis_FinalizeCleanup(pContext);

    if (pContext->SendLock.SpinLock)
    {
        NdisFreeSpinLock(&pContext->SendLock);
    }

#if !defined(UNIFY_LOCKS)
    if (pContext->ReceiveLock.SpinLock)
    {
        NdisFreeSpinLock(&pContext->ReceiveLock);
    }
#endif

    /* free queue shared memory */
    for (i = 0; i < MAX_NUM_OF_QUEUES; i++) {
        if (pContext->SharedMemoryRanges[i].pBase != NULL) {
            NdisMFreeSharedMemory(
                pContext->MiniportHandle,
                pContext->SharedMemoryRanges[i].uLength,
                TRUE /* Cached */,
                pContext->SharedMemoryRanges[i].pBase,
                pContext->SharedMemoryRanges[i].BasePA);
            pContext->SharedMemoryRanges[i].pBase = NULL;
        }
    }

    /* unmap our port and memory IO resources */
    for (i = 0; i < PCI_TYPE0_ADDRESSES; i++)
    {
       tBusResource *pRes = &pContext->AdapterResources.PciBars[i];
       if (pRes->pBase != NULL)
       {
          if (pRes->bPortSpace)
          {
             NdisMDeregisterIoPortRange(
                pContext->MiniportHandle,
                pRes->BasePA.LowPart,
                pRes->uLength,
                pRes->pBase);
          }
          else
          {
             NdisMUnmapIoSpace(
                pContext->MiniportHandle,
                pRes->pBase,
                pRes->uLength);
          }
       }
    }
}


/**********************************************************
System shutdown handler (shutdown, restart, bugcheck)
Parameters:
    context
***********************************************************/
VOID ParaNdis_OnShutdown(PARANDIS_ADAPTER *pContext)
{
    DEBUG_ENTRY(0); // this is only for kdbg :)
    ParaNdis_ResetVirtIONetDevice(pContext);
}

/**********************************************************
Handles hardware interrupt
Parameters:
    context
    ULONG knownInterruptSources - bitmask of
Return value:
    TRUE, if it is our interrupt
    sets *pRunDpc to TRUE if the DPC should be fired
***********************************************************/
BOOLEAN ParaNdis_OnLegacyInterrupt(
    PARANDIS_ADAPTER *pContext,
    OUT BOOLEAN *pRunDpc)
{
    ULONG status = virtio_read_isr_status(&pContext->IODevice);

    if((status == 0)                                   ||
       (status == VIRTIO_NET_INVALID_INTERRUPT_STATUS) ||
       (pContext->powerState != NdisDeviceStateD0))
    {
        *pRunDpc = FALSE;
        return FALSE;
    }

    PARANDIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext);
    ParaNdis_VirtIODisableIrqSynchronized(pContext, isAny);
    InterlockedOr(&pContext->InterruptStatus, (LONG) ((status & isControl) | isReceive | isTransmit));
    *pRunDpc = TRUE;
    return TRUE;
}

BOOLEAN ParaNdis_OnQueuedInterrupt(
    PARANDIS_ADAPTER *pContext,
    OUT BOOLEAN *pRunDpc,
    ULONG knownInterruptSources)
{
    struct virtqueue* _vq = ParaNdis_GetQueueForInterrupt(pContext, knownInterruptSources);

    /* If interrupts for this queue disabled do nothing */
    if((_vq != NULL) && !ParaNDIS_IsQueueInterruptEnabled(_vq))
    {
        *pRunDpc = FALSE;
    }
    else
    {
        PARANDIS_STORE_LAST_INTERRUPT_TIMESTAMP(pContext);
        InterlockedOr(&pContext->InterruptStatus, (LONG)knownInterruptSources);
        ParaNdis_VirtIODisableIrqSynchronized(pContext, knownInterruptSources);
        *pRunDpc = TRUE;
    }

    return *pRunDpc;
}


/**********************************************************
It is called from Rx processing routines in regular mode of operation.
Returns received buffer back to VirtIO queue, inserting it to NetReceiveBuffers.
If needed, signals end of RX pause operation

Must be called with &pContext->ReceiveLock acquired

Parameters:
    context
    void *pDescriptor - pIONetDescriptor to return
***********************************************************/
void ReuseReceiveBufferRegular(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBuffersDescriptor)
{
    DEBUG_ENTRY(4);

    if(!pBuffersDescriptor)
        return;

    RemoveEntryList(&pBuffersDescriptor->listEntry);

    if(AddRxBufferToQueue(pContext, pBuffersDescriptor))
    {
        InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry);

        pContext->NetNofReceiveBuffers++;

        if (pContext->NetNofReceiveBuffers > pContext->NetMaxReceiveBuffers)
        {
            DPrintf(0, (" Error: NetNofReceiveBuffers > NetMaxReceiveBuffers(%d>%d)",
                pContext->NetNofReceiveBuffers, pContext->NetMaxReceiveBuffers));
        }

        if (++pContext->Counters.nReusedRxBuffers >= pContext->Limits.nReusedRxBuffers)
        {
            pContext->Counters.nReusedRxBuffers = 0;
            virtqueue_kick_always(pContext->NetReceiveQueue);
        }

        if (IsListEmpty(&pContext->NetReceiveBuffersWaiting))
        {
            if (pContext->ReceiveState == srsPausing || pContext->ReceivePauseCompletionProc)
            {
                ONPAUSECOMPLETEPROC callback = pContext->ReceivePauseCompletionProc;
                pContext->ReceiveState = srsDisabled;
                pContext->ReceivePauseCompletionProc = NULL;
                ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
                if (callback) callback(pContext);
            }
        }
    }
    else
    {
        DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!"));
        VirtIONetFreeBufferDescriptor(pContext, pBuffersDescriptor);
        pContext->NetMaxReceiveBuffers--;
    }
}

/**********************************************************
It is called from Rx processing routines between power off and power on in non-paused mode (Win8).
Returns received buffer to NetReceiveBuffers. 
All the buffers will be placed into Virtio queue during power-on procedure

Must be called with &pContext->ReceiveLock acquired

Parameters:
    context
    void *pDescriptor - pIONetDescriptor to return
***********************************************************/
static void ReuseReceiveBufferPowerOff(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBuffersDescriptor)
{
    RemoveEntryList(&pBuffersDescriptor->listEntry);
    InsertTailList(&pContext->NetReceiveBuffers, &pBuffersDescriptor->listEntry);
}

/**********************************************************
It is called from Tx processing routines
Gets all the finished buffer from VirtIO TX path and
returns them to NetFreeSendBuffers

Must be called with &pContext->SendLock acquired

Parameters:
    context
Return value:
    (for reference) number of TX buffers returned
***********************************************************/
UINT ParaNdis_VirtIONetReleaseTransmitBuffers(
    PARANDIS_ADAPTER *pContext)
{
    UINT len, i = 0;
    pIONetDescriptor pBufferDescriptor;

    DEBUG_ENTRY(4);

    while(NULL != (pBufferDescriptor = virtqueue_get_buf(pContext->NetSendQueue, &len)))
    {
        RemoveEntryList(&pBufferDescriptor->listEntry);
        pContext->nofFreeTxDescriptors++;
        if (!pBufferDescriptor->nofUsedBuffers)
        {
            DPrintf(0, ("[%s] ERROR: nofUsedBuffers not set!", __FUNCTION__));
        }
        pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers;
        ParaNdis_OnTransmitBufferReleased(pContext, pBufferDescriptor);
        InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry);
        DPrintf(3, ("[%s] Free Tx: desc %d, buff %d", __FUNCTION__, pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers));
        pBufferDescriptor->nofUsedBuffers = 0;
        ++i;
    }
    if (i)
    {
        NdisGetCurrentSystemTime(&pContext->LastTxCompletionTimeStamp);
        pContext->bDoKickOnNoBuffer = TRUE;
        pContext->nDetectedStoppedTx = 0;
    }
    DEBUG_EXIT_STATUS((i ? 3 : 5), i);
    return i;
}

static ULONG FORCEINLINE QueryTcpHeaderOffset(PVOID packetData, ULONG ipHeaderOffset, ULONG ipPacketLength)
{
    ULONG res;
    tTcpIpPacketParsingResult ppr = ParaNdis_ReviewIPPacket(
        (PUCHAR)packetData + ipHeaderOffset,
        ipPacketLength,
        __FUNCTION__);
    if (ppr.xxpStatus == ppresXxpKnown)
    {
        res = ipHeaderOffset + ppr.ipHeaderSize;
    }
    else
    {
        DPrintf(0, ("[%s] ERROR: NOT a TCP or UDP packet - expected troubles!", __FUNCTION__));
        res = 0;
    }
    return res;
}


/*********************************************************
Called with from ProcessTx routine with TxLock held
Uses pContext->sgTxGatherTable
***********************************************************/
tCopyPacketResult ParaNdis_DoSubmitPacket(PARANDIS_ADAPTER *pContext, tTxOperationParameters *Params)
{
    tCopyPacketResult result;
    tMapperResult mapResult = {0,0,0};
    // populating priority tag or LSO MAY require additional SG element
    UINT nRequiredBuffers;
    BOOLEAN bUseCopy = FALSE;
    struct VirtIOBufferDescriptor *sg = pContext->sgTxGatherTable;<--- Assignment 'sg=pContext->sgTxGatherTable', assigned value is 0<--- Assignment 'sg=pContext->sgTxGatherTable', assigned value is 0<--- Assignment 'sg=pContext->sgTxGatherTable', assigned value is 0

    nRequiredBuffers = Params->nofSGFragments + 1 + ((Params->flags & (pcrPriorityTag | pcrLSO)) ? 1 : 0);

    result.size = 0;
    result.error = cpeOK;
    if (!pContext->bUseScatterGather ||         // only copy available
        Params->nofSGFragments == 0 ||          // theoretical case
        !sg ||                                  // only copy available<--- Assuming that condition '!sg' is not redundant<--- Assuming that condition '!sg' is not redundant<--- Assuming that condition '!sg' is not redundant
        ((~Params->flags & pcrLSO) && nRequiredBuffers > pContext->maxFreeHardwareBuffers) // to many fragments and normal size of packet
        )
    {
        nRequiredBuffers = 2;
        bUseCopy = TRUE;
    }
    else if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect))
    {
        nRequiredBuffers = 1;
    }

    // I do not think this will help, but at least we can try freeing some buffers right now
    if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors)
    {
        ParaNdis_VirtIONetReleaseTransmitBuffers(pContext);
    }

    if (nRequiredBuffers > pContext->maxFreeHardwareBuffers)
    {
        // LSO and too many buffers, impossible to send
        result.error = cpeTooLarge;
        DPrintf(0, ("[%s] ERROR: too many fragments(%d required, %d max.avail)!", __FUNCTION__,
            nRequiredBuffers, pContext->maxFreeHardwareBuffers));
    }
    else if (pContext->nofFreeHardwareBuffers < nRequiredBuffers || !pContext->nofFreeTxDescriptors)
    {
        virtqueue_enable_cb_delayed(pContext->NetSendQueue);
        result.error = cpeNoBuffer;
    }
    else if (Params->offloadMss && bUseCopy)
    {
        result.error = cpeInternalError;
        DPrintf(0, ("[%s] ERROR: expecting SG for TSO! (%d buffers, %d bytes)", __FUNCTION__,
            Params->nofSGFragments, Params->ulDataSize));
    }
    else if (bUseCopy)
    {
        result = ParaNdis_DoCopyPacketData(pContext, Params);
    }
    else
    {
        UINT nMappedBuffers;
        ULONGLONG paOfIndirectArea = 0;
        PVOID vaOfIndirectArea = NULL;
        pIONetDescriptor pBuffersDescriptor = (pIONetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers);
        pContext->nofFreeTxDescriptors--;
        NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size);
        sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical;<--- Null pointer dereference
        sg[0].length = pBuffersDescriptor->HeaderInfo.size;<--- Null pointer dereference
        ParaNdis_PacketMapper(
            pContext,
            Params->packet,
            Params->ReferenceValue,
            sg + 1,<--- Null pointer addition
            pBuffersDescriptor,
            &mapResult);
        nMappedBuffers = mapResult.usBuffersMapped;
        if (nMappedBuffers)
        {
            nMappedBuffers++;
            if (pContext->bUseIndirect && !(Params->flags & pcrNoIndirect))
            {
                ULONG space1 = (mapResult.usBufferSpaceUsed + 7) & ~7;
                ULONG space2 = nMappedBuffers * SIZE_OF_SINGLE_INDIRECT_DESC;
                if (pBuffersDescriptor->DataInfo.size >= (space1 + space2))
                {
                    vaOfIndirectArea = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, space1);
                    paOfIndirectArea = pBuffersDescriptor->DataInfo.Physical.QuadPart + space1;
                    pContext->extraStatistics.framesIndirect++;
                }
                else if (nMappedBuffers <= pContext->nofFreeHardwareBuffers)
                {
                    // send as is, no indirect
                }
                else
                {
                    result.error = cpeNoIndirect;
                    DPrintf(0, ("[%s] Unexpected ERROR of placement!", __FUNCTION__));
                }
            }
            if (result.error == cpeOK)
            {
                if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum))
                {
                    unsigned short addPriorityLen = (Params->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0;
                    if (pContext->bDoHardwareChecksum)
                    {
                        virtio_net_hdr_basic *pheader = pBuffersDescriptor->HeaderInfo.Virtual;
                        pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
                        if (!Params->tcpHeaderOffset)
                        {
                            Params->tcpHeaderOffset = QueryTcpHeaderOffset(
                                pBuffersDescriptor->DataInfo.Virtual,
                                pContext->Offload.ipHeaderOffset + addPriorityLen,
                                mapResult.usBufferSpaceUsed - pContext->Offload.ipHeaderOffset - addPriorityLen);
                        }
                        else
                        {
                            Params->tcpHeaderOffset += addPriorityLen;
                        }
                        pheader->csum_start = (USHORT)Params->tcpHeaderOffset;
                        pheader->csum_offset = (Params->flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET;
                    }
                    else
                    {
                        // emulation mode - it is slow and intended only for test of flows
                        // and debugging of WLK test cases
                        PVOID pCopy = ParaNdis_AllocateMemory(pContext, Params->ulDataSize);
                        if (pCopy)
                        {
                            tTcpIpPacketParsingResult ppr;
                            // duplicate entire packet
                            ParaNdis_PacketCopier(Params->packet, pCopy, Params->ulDataSize, Params->ReferenceValue, FALSE);
                            // calculate complete TCP/UDP checksum
                            ppr = ParaNdis_CheckSumVerify(
                                RtlOffsetToPointer(pCopy, pContext->Offload.ipHeaderOffset + addPriorityLen),
                                Params->ulDataSize - pContext->Offload.ipHeaderOffset - addPriorityLen,
                                pcrAnyChecksum | pcrFixXxpChecksum,
                                __FUNCTION__);
                            // data portion in aside buffer contains complete IP+TCP header
                            // rewrite copy of original buffer by one new with calculated data
                            NdisMoveMemory(
                                pBuffersDescriptor->DataInfo.Virtual,
                                pCopy,
                                mapResult.usBufferSpaceUsed);
                            NdisFreeMemory(pCopy, 0, 0);
                        }
                    }
                }

                if (0 <= virtqueue_add_buf(
                    pContext->NetSendQueue,
                    sg,
                    nMappedBuffers,
                    0,
                    pBuffersDescriptor,
                    vaOfIndirectArea,
                    paOfIndirectArea))
                {
                    pBuffersDescriptor->nofUsedBuffers = nMappedBuffers;
                    pContext->nofFreeHardwareBuffers -= nMappedBuffers;
                    if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers)
                        pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers;
                    pBuffersDescriptor->ReferenceValue = Params->ReferenceValue;
                    result.size = Params->ulDataSize;
                    DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs",
                        __FUNCTION__, nMappedBuffers, result.size,
                        pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers
                    ));
                }
                else
                {
                    result.error = cpeInternalError;
                    DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__));
                }
            }
        }
        else
        {
            DPrintf(0, ("[%s] Unexpected ERROR: packet not mapped!", __FUNCTION__));
            result.error = cpeInternalError;
        }

        if (result.error == cpeOK)
        {
            UCHAR ethernetHeader[sizeof(ETH_HEADER)];
            eInspectedPacketType packetType;
            /* get the ethernet header for review */
            ParaNdis_PacketCopier(Params->packet, ethernetHeader, sizeof(ethernetHeader), Params->ReferenceValue, TRUE);
            packetType = QueryPacketType(ethernetHeader);
            DebugDumpPacket("sending", ethernetHeader, 3);
            InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry);
            pContext->Statistics.ifHCOutOctets += result.size;
            switch (packetType)
            {
                case iptBroadcast:
                    pContext->Statistics.ifHCOutBroadcastOctets += result.size;
                    pContext->Statistics.ifHCOutBroadcastPkts++;
                    break;
                case iptMulticast:
                    pContext->Statistics.ifHCOutMulticastOctets += result.size;
                    pContext->Statistics.ifHCOutMulticastPkts++;
                    break;
                default:
                    pContext->Statistics.ifHCOutUcastOctets += result.size;
                    pContext->Statistics.ifHCOutUcastPkts++;
                    break;
            }

            if (Params->flags & pcrLSO)
                pContext->extraStatistics.framesLSO++;
        }
        else
        {
            pContext->nofFreeTxDescriptors++;
            InsertHeadList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry);
        }
    }
    if (result.error == cpeNoBuffer && pContext->bDoKickOnNoBuffer)
    {
        virtqueue_kick_always(pContext->NetSendQueue);
        pContext->bDoKickOnNoBuffer = FALSE;
    }
    if (result.error == cpeOK)
    {
        if (Params->flags & (pcrTcpChecksum | pcrUdpChecksum))
            pContext->extraStatistics.framesCSOffload++;
    }
    return result;
}


/**********************************************************
It is called from Tx processing routines
Prepares the VirtIO buffer and copies to it the data from provided packet

Must be called with &pContext->SendLock acquired

Parameters:
    context
    tPacketType packet          specific type is NDIS dependent
    tCopyPacketDataFunction     PacketCopier procedure for NDIS-specific type of packet
Return value:
    (for reference) number of TX buffers returned
***********************************************************/
tCopyPacketResult ParaNdis_DoCopyPacketData(
    PARANDIS_ADAPTER *pContext,
    tTxOperationParameters *pParams)
{
    tCopyPacketResult result;
    tCopyPacketResult CopierResult;
    struct VirtIOBufferDescriptor sg[2];
    pIONetDescriptor pBuffersDescriptor = NULL;
    ULONG flags = pParams->flags;
    UINT nRequiredHardwareBuffers = 2;
    result.size  = 0;
    result.error = cpeOK;
    if (pContext->nofFreeHardwareBuffers < nRequiredHardwareBuffers ||
        IsListEmpty(&pContext->NetFreeSendBuffers))
    {
        result.error = cpeNoBuffer;
    }
    if(result.error == cpeOK)
    {
        pBuffersDescriptor = (pIONetDescriptor)RemoveHeadList(&pContext->NetFreeSendBuffers);
        NdisZeroMemory(pBuffersDescriptor->HeaderInfo.Virtual, pBuffersDescriptor->HeaderInfo.size);
        sg[0].physAddr = pBuffersDescriptor->HeaderInfo.Physical;
        sg[0].length = pBuffersDescriptor->HeaderInfo.size;
        sg[1].physAddr = pBuffersDescriptor->DataInfo.Physical;
        CopierResult = ParaNdis_PacketCopier(
            pParams->packet,
            pBuffersDescriptor->DataInfo.Virtual,
            pBuffersDescriptor->DataInfo.size,
            pParams->ReferenceValue,
            FALSE);
        sg[1].length = result.size = CopierResult.size;
        // did NDIS ask us to compute CS?
        if ((flags & (pcrTcpChecksum | pcrUdpChecksum | pcrIpChecksum)) != 0)
        {
            // we asked
            unsigned short addPriorityLen = (pParams->flags & pcrPriorityTag) ? ETH_PRIORITY_HEADER_SIZE : 0;
            PVOID ipPacket = RtlOffsetToPointer(
                pBuffersDescriptor->DataInfo.Virtual, pContext->Offload.ipHeaderOffset + addPriorityLen);
            ULONG ipPacketLength = CopierResult.size - pContext->Offload.ipHeaderOffset - addPriorityLen;
            if (!pParams->tcpHeaderOffset &&
                (flags & (pcrTcpChecksum | pcrUdpChecksum)) )
            {
                pParams->tcpHeaderOffset = QueryTcpHeaderOffset(
                    pBuffersDescriptor->DataInfo.Virtual,
                    pContext->Offload.ipHeaderOffset + addPriorityLen,
                    ipPacketLength);
            }
            else
            {
                pParams->tcpHeaderOffset += addPriorityLen;
            }

            if (pContext->bDoHardwareChecksum)
            {
                if (flags & (pcrTcpChecksum | pcrUdpChecksum))
                {
                    // hardware offload
                    virtio_net_hdr_basic *pvnh = (virtio_net_hdr_basic *)pBuffersDescriptor->HeaderInfo.Virtual;
                    pvnh->csum_start = (USHORT)pParams->tcpHeaderOffset;
                    pvnh->csum_offset = (flags & pcrTcpChecksum) ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET;
                    pvnh->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM;
                }
                if (flags & (pcrIpChecksum))
                {
                    ParaNdis_CheckSumVerify(
                        ipPacket,
                        ipPacketLength,
                        pcrIpChecksum | pcrFixIPChecksum,
                        __FUNCTION__);
                }
            }
            else if (CopierResult.size > pContext->Offload.ipHeaderOffset)
            {
                ULONG csFlags = 0;
                if (flags & pcrIpChecksum) csFlags |= pcrIpChecksum | pcrFixIPChecksum;
                if (flags & (pcrTcpChecksum | pcrUdpChecksum)) csFlags |= pcrTcpChecksum | pcrUdpChecksum| pcrFixXxpChecksum;
                // software offload
                ParaNdis_CheckSumVerify(
                    ipPacket,
                    ipPacketLength,
                    csFlags,
                    __FUNCTION__);
            }
            else
            {
                DPrintf(0, ("[%s] ERROR: Invalid buffer size for offload!", __FUNCTION__));
                result.size = 0;
                result.error = cpeInternalError;
            }
        }
        pContext->nofFreeTxDescriptors--;
        if (result.size)
        {
            eInspectedPacketType packetType;
            packetType = QueryPacketType(pBuffersDescriptor->DataInfo.Virtual);
            DebugDumpPacket("sending", pBuffersDescriptor->DataInfo.Virtual, 3);

            pBuffersDescriptor->nofUsedBuffers = nRequiredHardwareBuffers;
            pContext->nofFreeHardwareBuffers -= nRequiredHardwareBuffers;
            if (pContext->minFreeHardwareBuffers > pContext->nofFreeHardwareBuffers)
                pContext->minFreeHardwareBuffers = pContext->nofFreeHardwareBuffers;
            if (0 > virtqueue_add_buf(
                pContext->NetSendQueue,
                sg,
                2,
                0,
                pBuffersDescriptor,
                NULL,
                0
                ))
            {
                pBuffersDescriptor->nofUsedBuffers = 0;
                pContext->nofFreeHardwareBuffers += nRequiredHardwareBuffers;
                result.error = cpeInternalError;
                result.size  = 0;
                DPrintf(0, ("[%s] Unexpected ERROR adding buffer to TX engine!..", __FUNCTION__));
            }
            else
            {
                DPrintf(2, ("[%s] Submitted %d buffers (%d bytes), avail %d desc, %d bufs",
                    __FUNCTION__, nRequiredHardwareBuffers, result.size,
                    pContext->nofFreeTxDescriptors, pContext->nofFreeHardwareBuffers
                ));
            }
            if (result.error != cpeOK)
            {
                InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry);
                pContext->nofFreeTxDescriptors++;
            }
            else
            {
                ULONG reportedSize = pParams->ulDataSize;
                pBuffersDescriptor->ReferenceValue = pParams->ReferenceValue;
                InsertTailList(&pContext->NetSendBuffersInUse, &pBuffersDescriptor->listEntry);
                pContext->Statistics.ifHCOutOctets += reportedSize;
                switch (packetType)
                {
                    case iptBroadcast:
                        pContext->Statistics.ifHCOutBroadcastOctets += reportedSize;
                        pContext->Statistics.ifHCOutBroadcastPkts++;
                        break;
                    case iptMulticast:
                        pContext->Statistics.ifHCOutMulticastOctets += reportedSize;
                        pContext->Statistics.ifHCOutMulticastPkts++;
                        break;
                    default:
                        pContext->Statistics.ifHCOutUcastOctets += reportedSize;
                        pContext->Statistics.ifHCOutUcastPkts++;
                        break;
                }
            }
        }
        else
        {
            DPrintf(0, ("[%s] Unexpected ERROR in copying packet data! Continue...", __FUNCTION__));
            InsertTailList(&pContext->NetFreeSendBuffers, &pBuffersDescriptor->listEntry);
            pContext->nofFreeTxDescriptors++;
            // the buffer is not copied and the callback will not be called
            result.error = cpeInternalError;
        }
    }

    return result;
}

static ULONG ShallPassPacket(PARANDIS_ADAPTER *pContext, PVOID address, UINT len, eInspectedPacketType *pType)
{
    ULONG b;
    if (len <= sizeof(ETH_HEADER)) return FALSE;
    if (len > pContext->MaxPacketSize.nMaxFullSizeHwRx) return FALSE;
    if (len > pContext->MaxPacketSize.nMaxFullSizeOS && !ETH_HAS_PRIO_HEADER(address)) return FALSE;
    *pType = QueryPacketType(address);
    if (pContext->PacketFilter & NDIS_PACKET_TYPE_PROMISCUOUS)  return TRUE;

    switch(*pType)
    {
        case iptBroadcast:
            b = pContext->PacketFilter & NDIS_PACKET_TYPE_BROADCAST;
            break;
        case iptMulticast:
            b = pContext->PacketFilter & NDIS_PACKET_TYPE_ALL_MULTICAST;
            if (!b && (pContext->PacketFilter & NDIS_PACKET_TYPE_MULTICAST))
            {
                UINT i, n = pContext->MulticastData.nofMulticastEntries * ETH_LENGTH_OF_ADDRESS;
                b = 1;
                for (i = 0; b && i < n; i += ETH_LENGTH_OF_ADDRESS)
                {
                    ETH_COMPARE_NETWORK_ADDRESSES((PUCHAR)address, &pContext->MulticastData.MulticastList[i], &b)
                }
                b = !b;
            }
            break;
        default:
            ETH_COMPARE_NETWORK_ADDRESSES((PUCHAR)address, pContext->CurrentMacAddress, &b);
            b = !b && (pContext->PacketFilter & NDIS_PACKET_TYPE_DIRECTED);
            break;
    }
    if (!b)
    {
        pContext->extraStatistics.framesFilteredOut++;
    }
    return b;
}

void
ParaNdis_PadPacketReceived(PVOID pDataBuffer, PULONG pLength)
{
    // Ethernet standard declares minimal possible packet size
    // Packets smaller than that must be padded before transfer
    // Ethernet HW pads packets on transmit, however in our case
    // some packets do not travel over Ethernet but being routed
    // guest-to-guest by virtual switch.
    // In this case padding is not performed and we may
    // receive packet smaller than minimal allowed size. This is not
    // a problem for real life scenarios however WHQL/HCK contains
    // tests that check padding of received packets.
    // To make these tests happy we have to pad small packets on receive

    //NOTE: This function assumes that VLAN header has been already stripped out

    if(*pLength < ETH_MIN_PACKET_SIZE)
    {
        RtlZeroMemory(RtlOffsetToPointer(pDataBuffer, *pLength), ETH_MIN_PACKET_SIZE - *pLength);
        *pLength = ETH_MIN_PACKET_SIZE;
    }
}

/**********************************************************
Manages RX path, calling NDIS-specific procedure for packet indication
Parameters:
    context
***********************************************************/
static UINT ParaNdis_ProcessRxPath(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate)
{
    pIONetDescriptor pBuffersDescriptor;
    UINT len, headerSize = pContext->nVirtioHeaderSize;
    eInspectedPacketType packetType = iptInvalid;
    UINT nReceived = 0, nRetrieved = 0, nReported = 0;
    tPacketIndicationType   *pBatchOfPackets;
    UINT                    maxPacketsInBatch = pContext->NetMaxReceiveBuffers;
    pBatchOfPackets = pContext->bBatchReceive ?
        ParaNdis_AllocateMemory(pContext, maxPacketsInBatch * sizeof(tPacketIndicationType)) : NULL;
    NdisAcquireSpinLock(&pContext->ReceiveLock);
    while ((nReported < ulMaxPacketsToIndicate) && NULL != (pBuffersDescriptor = virtqueue_get_buf(pContext->NetReceiveQueue, &len)))
    {
        PVOID pDataBuffer = RtlOffsetToPointer(pBuffersDescriptor->DataInfo.Virtual, pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0);
        RemoveEntryList(&pBuffersDescriptor->listEntry);
        InsertTailList(&pContext->NetReceiveBuffersWaiting, &pBuffersDescriptor->listEntry);
        pContext->NetNofReceiveBuffers--;
        nRetrieved++;
        DPrintf(2, ("[%s] retrieved header+%d b.", __FUNCTION__, len - headerSize));
        DebugDumpPacket("receive", pDataBuffer, 3);

        if( !pContext->bSurprizeRemoved &&
            ShallPassPacket(pContext, pDataBuffer, len - headerSize, &packetType) &&
            pContext->ReceiveState == srsEnabled &&
            pContext->bConnected)
        {
            BOOLEAN b = FALSE;
            ULONG length = len - headerSize;
            if (!pBatchOfPackets)
            {
                NdisReleaseSpinLock(&pContext->ReceiveLock);
                b = NULL != ParaNdis_IndicateReceivedPacket(
                    pContext,
                    pDataBuffer,
                    &length,
                    FALSE,
                    pBuffersDescriptor);
                NdisAcquireSpinLock(&pContext->ReceiveLock);
            }
            else
            {
                tPacketIndicationType packet;
                packet = ParaNdis_IndicateReceivedPacket(
                    pContext,
                    pDataBuffer,
                    &length,
                    TRUE,
                    pBuffersDescriptor);
                b = packet != NULL;
                if (b) pBatchOfPackets[nReceived] = packet;
            }
            if (!b)
            {
                pContext->ReuseBufferProc(pContext, pBuffersDescriptor);
                //only possible reason for that is unexpected Vlan tag
                //shall I count it as error?
                pContext->Statistics.ifInErrors++;
                pContext->Statistics.ifInDiscards++;
            }
            else
            {
                nReceived++;
                nReported++;
                pContext->Statistics.ifHCInOctets += length;
                switch(packetType)
                {
                    case iptBroadcast:
                        pContext->Statistics.ifHCInBroadcastPkts++;
                        pContext->Statistics.ifHCInBroadcastOctets += length;
                        break;
                    case iptMulticast:
                        pContext->Statistics.ifHCInMulticastPkts++;
                        pContext->Statistics.ifHCInMulticastOctets += length;
                        break;
                    default:
                        pContext->Statistics.ifHCInUcastPkts++;
                        pContext->Statistics.ifHCInUcastOctets += length;
                        break;
                }
                if (pBatchOfPackets && nReceived == maxPacketsInBatch)
                {
                    DPrintf(1, ("[%s] received %d buffers of max %d", __FUNCTION__, nReceived, ulMaxPacketsToIndicate));
                    NdisReleaseSpinLock(&pContext->ReceiveLock);
                    ParaNdis_IndicateReceivedBatch(pContext, pBatchOfPackets, nReceived);
                    NdisAcquireSpinLock(&pContext->ReceiveLock);
                    nReceived = 0;
                }
            }
        }
        else
        {
            // reuse packet, there is no data or the RX is suppressed
            pContext->ReuseBufferProc(pContext, pBuffersDescriptor);
        }
    }
    ParaNdis_DebugHistory(pContext, hopReceiveStat, NULL, nRetrieved, nReported, pContext->NetNofReceiveBuffers);
    NdisReleaseSpinLock(&pContext->ReceiveLock);
    if (nReceived && pBatchOfPackets)
    {
        DPrintf(1, ("[%s]%d: received %d buffers of max %d", __FUNCTION__, KeGetCurrentProcessorNumber(), nReceived, ulMaxPacketsToIndicate));
        ParaNdis_IndicateReceivedBatch(pContext, pBatchOfPackets, nReceived);
    }
    if (pBatchOfPackets) NdisFreeMemory(pBatchOfPackets, 0, 0);
    return nReported;
}

void ParaNdis_ReportLinkStatus(PARANDIS_ADAPTER *pContext, BOOLEAN bForce)
{
    BOOLEAN bConnected = TRUE;
    if (pContext->bLinkDetectSupported)
    {
        USHORT linkStatus = 0;
        USHORT offset = sizeof(pContext->CurrentMacAddress);
        // link changed
        virtio_get_config(&pContext->IODevice, offset, &linkStatus, sizeof(linkStatus));
        bConnected = (linkStatus & VIRTIO_NET_S_LINK_UP) != 0;
    }
    ParaNdis_IndicateConnect(pContext, bConnected, bForce);
}

static BOOLEAN RestartQueueSynchronously(tSynchronizedContext *SyncContext)
{
    struct virtqueue * _vq = (struct virtqueue *) SyncContext->Parameter;
    bool res = true;
    if (!virtqueue_enable_cb(_vq))
    {
        virtqueue_disable_cb(_vq);
        res = false;
    }

    ParaNdis_DebugHistory(SyncContext->pContext, hopDPC, (PVOID)SyncContext->Parameter, 0x20, res, 0);
    return !res;
}
/**********************************************************
DPC implementation, common for both NDIS
Parameters:
    context
***********************************************************/
ULONG ParaNdis_DPCWorkBody(PARANDIS_ADAPTER *pContext, ULONG ulMaxPacketsToIndicate)
{
    ULONG stillRequiresProcessing = 0;
    ULONG interruptSources;
    UINT uIndicatedRXPackets = 0;
    UINT numOfPacketsToIndicate = min(ulMaxPacketsToIndicate, pContext->uNumberOfHandledRXPacketsInDPC);

    DEBUG_ENTRY(5);
    if (pContext->bEnableInterruptHandlingDPC)
    {
        InterlockedIncrement(&pContext->counterDPCInside);
        if (pContext->bEnableInterruptHandlingDPC)
        {
            BOOLEAN bDoKick = FALSE;

            InterlockedExchange(&pContext->bDPCInactive, 0);
            interruptSources = InterlockedExchange(&pContext->InterruptStatus, 0);
            ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)1, interruptSources, 0, 0);
            if ((interruptSources & isControl) && pContext->bLinkDetectSupported)
            {
                ParaNdis_ReportLinkStatus(pContext, FALSE);
            }
            if (interruptSources & isTransmit)
            {
                bDoKick = ParaNdis_ProcessTx(pContext, TRUE, TRUE);
            }
            if (interruptSources & isReceive)
            {
                int nRestartResult = 0;

                do
                {
                    LONG rxActive = InterlockedIncrement(&pContext->dpcReceiveActive);
                    if (rxActive == 1)
                    {
                        uIndicatedRXPackets += ParaNdis_ProcessRxPath(pContext, numOfPacketsToIndicate - uIndicatedRXPackets);
                        InterlockedDecrement(&pContext->dpcReceiveActive);
                        NdisAcquireSpinLock(&pContext->ReceiveLock);
                        nRestartResult = ParaNdis_SynchronizeWithInterrupt(
                            pContext, pContext->ulRxMessage, RestartQueueSynchronously, pContext->NetReceiveQueue);
                        ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)3, nRestartResult, 0, 0);
                        NdisReleaseSpinLock(&pContext->ReceiveLock);
                        DPrintf(nRestartResult ? 2 : 6, ("[%s] queue restarted%s", __FUNCTION__, nRestartResult ? "(Rerun)" : "(Done)"));

                        if (uIndicatedRXPackets < numOfPacketsToIndicate)
                        {

                        }
                        else if (uIndicatedRXPackets == numOfPacketsToIndicate)
                        {
                            DPrintf(1, ("[%s] Breaking Rx loop after %d indications", __FUNCTION__, uIndicatedRXPackets));
                            ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)4, nRestartResult, 0, 0);
                            break;
                        }
                        else
                        {
                            DPrintf(0, ("[%s] Glitch found: %d allowed, %d indicated", __FUNCTION__, numOfPacketsToIndicate, uIndicatedRXPackets));
                            ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)6, nRestartResult, 0, 0);
                        }
                    }
                    else
                    {
                        InterlockedDecrement(&pContext->dpcReceiveActive);
                        if (!nRestartResult)
                        {
                            NdisAcquireSpinLock(&pContext->ReceiveLock);
                            nRestartResult = ParaNdis_SynchronizeWithInterrupt(
                                pContext, pContext->ulRxMessage, RestartQueueSynchronously, pContext->NetReceiveQueue);
                            ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)5, nRestartResult, 0, 0);
                            NdisReleaseSpinLock(&pContext->ReceiveLock);
                        }
                        DPrintf(1, ("[%s] Skip Rx processing no.%d", __FUNCTION__, rxActive));
                        break;
                    }
                } while (nRestartResult);

                if (nRestartResult) stillRequiresProcessing |= isReceive;
            }

            if (interruptSources & isTransmit)
            {
                NdisAcquireSpinLock(&pContext->SendLock);
                if (ParaNdis_SynchronizeWithInterrupt(pContext, pContext->ulTxMessage, RestartQueueSynchronously, pContext->NetSendQueue))
                    stillRequiresProcessing |= isTransmit;
                if(bDoKick)
                {
#ifdef PARANDIS_TEST_TX_KICK_ALWAYS
                    virtqueue_kick_always(pContext->NetSendQueue);
#else
                    virtqueue_kick(pContext->NetSendQueue);
#endif
                }
                NdisReleaseSpinLock(&pContext->SendLock);
            }
        }
        InterlockedDecrement(&pContext->counterDPCInside);
        ParaNdis_DebugHistory(pContext, hopDPC, NULL, stillRequiresProcessing, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors);
    }
    return stillRequiresProcessing;
}

/**********************************************************
Periodically called procedure, checking dpc activity
If DPC are not running, it does exactly the same that the DPC
Parameters:
    context
***********************************************************/
static BOOLEAN CheckRunningDpc(PARANDIS_ADAPTER *pContext)
{
    BOOLEAN bStopped;
    BOOLEAN bReportHang = FALSE;
    bStopped = 0 != InterlockedExchange(&pContext->bDPCInactive, TRUE);

    if (bStopped)
    {
        pContext->nDetectedInactivity++;
        if (pContext->nEnableDPCChecker)
        {
            if (pContext->NetTxPacketsToReturn)
            {
                DPrintf(0, ("[%s] - NO ACTIVITY!", __FUNCTION__));
                if (!pContext->Limits.nPrintDiagnostic) PrintStatistics(pContext);
                if (pContext->nEnableDPCChecker > 1)
                {
                    int isrStatus1, isrStatus2;
                    isrStatus1 = virtio_read_isr_status(&pContext->IODevice);
                    isrStatus2 = virtio_read_isr_status(&pContext->IODevice);
                    if (isrStatus1 || isrStatus2)
                    {
                        DPrintf(0, ("WARNING: Interrupt status %d=>%d", isrStatus1, isrStatus2));
                    }
                }
                // simulateDPC
                InterlockedOr(&pContext->InterruptStatus, isAny);
                ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
            }
        }
    }
    else
    {
        pContext->nDetectedInactivity = 0;
    }

    NdisAcquireSpinLock(&pContext->SendLock);
    if (pContext->nofFreeHardwareBuffers != pContext->maxFreeHardwareBuffers)
    {
        if (pContext->nDetectedStoppedTx++ > 1)
        {
            DPrintf(0, ("[%s] - Suspicious Tx inactivity (%d)!", __FUNCTION__, pContext->nofFreeHardwareBuffers));
            //bReportHang = TRUE;
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
            WriteVirtIODeviceByte(pContext->IODevice.isr, 0);
#endif
        }
    }
    NdisReleaseSpinLock(&pContext->SendLock);


    if (pContext->Limits.nPrintDiagnostic &&
        ++pContext->Counters.nPrintDiagnostic >= pContext->Limits.nPrintDiagnostic)
    {
        pContext->Counters.nPrintDiagnostic = 0;
        // todo - collect more and put out optionally
        PrintStatistics(pContext);
    }

    if (pContext->Statistics.ifHCInOctets == pContext->Counters.prevIn)
    {
        pContext->Counters.nRxInactivity++;
        if (pContext->Counters.nRxInactivity >= 10)
        {
//#define CRASH_ON_NO_RX
#if defined(CRASH_ON_NO_RX)
            ONPAUSECOMPLETEPROC proc = (ONPAUSECOMPLETEPROC)(PVOID)1;
            proc(pContext);
#endif
        }
    }
    else
    {
        pContext->Counters.nRxInactivity = 0;
        pContext->Counters.prevIn = pContext->Statistics.ifHCInOctets;
    }
    return bReportHang;
}

/**********************************************************
Common implementation of periodic poll
Parameters:
    context
Return:
    TRUE, if reset required
***********************************************************/
BOOLEAN ParaNdis_CheckForHang(PARANDIS_ADAPTER *pContext)
{
    static int nHangOn = 0;
    BOOLEAN b = nHangOn >= 3 && nHangOn < 6;
    DEBUG_ENTRY(3);
    b |= CheckRunningDpc(pContext);
    //uncomment to cause 3 consecutive resets
    //nHangOn++;
    DEBUG_EXIT_STATUS(b ? 0 : 6, b);
    return b;
}

/**********************************************************
Common handler of multicast address configuration
Parameters:
    PVOID Buffer            array of addresses from NDIS
    ULONG BufferSize        size of incoming buffer
    PUINT pBytesRead        update on success
    PUINT pBytesNeeded      update on wrong buffer size
Return value:
    SUCCESS or kind of failure
***********************************************************/
NDIS_STATUS ParaNdis_SetMulticastList(
    PARANDIS_ADAPTER *pContext,
    PVOID Buffer,
    ULONG BufferSize,
    PUINT pBytesRead,
    PUINT pBytesNeeded)
{
    NDIS_STATUS status;
    ULONG length = BufferSize;
    if (length > sizeof(pContext->MulticastData.MulticastList))
    {
        status = NDIS_STATUS_MULTICAST_FULL;
        *pBytesNeeded = sizeof(pContext->MulticastData.MulticastList);
    }
    else if (length % ETH_LENGTH_OF_ADDRESS)
    {
        status = NDIS_STATUS_INVALID_LENGTH;
        *pBytesNeeded = (length / ETH_LENGTH_OF_ADDRESS) * ETH_LENGTH_OF_ADDRESS;
    }
    else
    {
        NdisZeroMemory(pContext->MulticastData.MulticastList, sizeof(pContext->MulticastData.MulticastList));
        if (length)
            NdisMoveMemory(pContext->MulticastData.MulticastList, Buffer, length);
        pContext->MulticastData.nofMulticastEntries = length / ETH_LENGTH_OF_ADDRESS;
        DPrintf(1, ("[%s] New multicast list of %d bytes", __FUNCTION__, length));
        *pBytesRead = length;
        status = NDIS_STATUS_SUCCESS;
    }
    return status;
}

/**********************************************************
Callable from synchronized routine or interrupt handler
to enable or disable Rx and/or Tx interrupt generation
Parameters:
    context
    interruptSource - isReceive, isTransmit
    b - 1/0 enable/disable
***********************************************************/
VOID ParaNdis_VirtIOEnableIrqSynchronized(PARANDIS_ADAPTER *pContext, ULONG interruptSource)
{
    if (interruptSource & isTransmit)
        virtqueue_enable_cb(pContext->NetSendQueue);
    if (interruptSource & isReceive)
        virtqueue_enable_cb(pContext->NetReceiveQueue);
    ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, TRUE, 0);
}

VOID ParaNdis_VirtIODisableIrqSynchronized(PARANDIS_ADAPTER *pContext, ULONG interruptSource)
{
    if (interruptSource & isTransmit)
        virtqueue_disable_cb(pContext->NetSendQueue);
    if (interruptSource & isReceive)
        virtqueue_disable_cb(pContext->NetReceiveQueue);
    ParaNdis_DebugHistory(pContext, hopDPC, (PVOID)0x10, interruptSource, FALSE, 0);
}

/**********************************************************
Common handler of PnP events
Parameters:
Return value:
***********************************************************/
VOID ParaNdis_OnPnPEvent(
    PARANDIS_ADAPTER *pContext,
    NDIS_DEVICE_PNP_EVENT pEvent,
    PVOID   pInfo,
    ULONG   ulSize)
{
    const char *pName = "";
    DEBUG_ENTRY(0);
#undef MAKECASE
#define MAKECASE(x) case (x): pName = #x; break;
    switch (pEvent)
    {
        MAKECASE(NdisDevicePnPEventQueryRemoved)
        MAKECASE(NdisDevicePnPEventRemoved)
        MAKECASE(NdisDevicePnPEventSurpriseRemoved)
        MAKECASE(NdisDevicePnPEventQueryStopped)
        MAKECASE(NdisDevicePnPEventStopped)
        MAKECASE(NdisDevicePnPEventPowerProfileChanged)
        default:
            break;
    }
    ParaNdis_DebugHistory(pContext, hopPnpEvent, NULL, pEvent, 0, 0);
    DPrintf(0, ("[%s] (%s)", __FUNCTION__, pName));
    if (pEvent == NdisDevicePnPEventSurpriseRemoved)
    {
        // on simulated surprise removal (under PnpTest) we need to reset the device
        // to prevent any access of device queues to memory buffers
        pContext->bSurprizeRemoved = TRUE;
        ParaNdis_ResetVirtIONetDevice(pContext);
    }
    pContext->PnpEvents[pContext->nPnpEventIndex++] = pEvent;
    if (pContext->nPnpEventIndex > sizeof(pContext->PnpEvents)/sizeof(pContext->PnpEvents[0]))
        pContext->nPnpEventIndex = 0;
}

static BOOLEAN SendControlMessage(
    PARANDIS_ADAPTER *pContext,
    UCHAR cls,
    UCHAR cmd,
    PVOID buffer1,
    ULONG size1,
    PVOID buffer2,
    ULONG size2,
    int levelIfOK
    )
{
    BOOLEAN bOK = FALSE;
    NdisAcquireSpinLock(&pContext->ReceiveLock);
    if (pContext->ControlData.Virtual && pContext->ControlData.size > (size1 + size2 + 16))
    {
        struct VirtIOBufferDescriptor sg[4];
        PUCHAR pBase = (PUCHAR)pContext->ControlData.Virtual;
        PHYSICAL_ADDRESS phBase = pContext->ControlData.Physical;
        ULONG offset = 0;
        UINT nOut = 1;

        ((virtio_net_ctrl_hdr *)pBase)->class_of_command = cls;
        ((virtio_net_ctrl_hdr *)pBase)->cmd = cmd;
        sg[0].physAddr = phBase;
        sg[0].length = sizeof(virtio_net_ctrl_hdr);
        offset += sg[0].length;
        offset = (offset + 3) & ~3;
        if (size1)
        {
            NdisMoveMemory(pBase + offset, buffer1, size1);
            sg[nOut].physAddr = phBase;
            sg[nOut].physAddr.QuadPart += offset;
            sg[nOut].length = size1;
            offset += size1;
            offset = (offset + 3) & ~3;
            nOut++;
        }
        if (size2)
        {
            NdisMoveMemory(pBase + offset, buffer2, size2);
            sg[nOut].physAddr = phBase;
            sg[nOut].physAddr.QuadPart += offset;
            sg[nOut].length = size2;
            offset += size2;
            offset = (offset + 3) & ~3;
            nOut++;
        }
        sg[nOut].physAddr = phBase;
        sg[nOut].physAddr.QuadPart += offset;
        sg[nOut].length = sizeof(virtio_net_ctrl_ack);
        *(virtio_net_ctrl_ack *)(pBase + offset) = VIRTIO_NET_ERR;

        if (0 <= virtqueue_add_buf(pContext->NetControlQueue, sg, nOut, 1, (PVOID)1, NULL, 0))
        {
            UINT len;
            void *p;
            virtqueue_kick_always(pContext->NetControlQueue);
            p = virtqueue_get_buf(pContext->NetControlQueue, &len);
            if (!p)
            {
                DPrintf(0, ("%s - ERROR: get_buf failed", __FUNCTION__));
            }
            else if (len != sizeof(virtio_net_ctrl_ack))
            {
                DPrintf(0, ("%s - ERROR: wrong len %d", __FUNCTION__, len));
            }
            else if (*(virtio_net_ctrl_ack *)(pBase + offset) != VIRTIO_NET_OK)
            {
                DPrintf(0, ("%s - ERROR: error %d returned", __FUNCTION__, *(virtio_net_ctrl_ack *)(pBase + offset)));
            }
            else
            {
                // everything is OK
                DPrintf(levelIfOK, ("%s OK(%d.%d,buffers of %d and %d) ", __FUNCTION__, cls, cmd, size1, size2));
                bOK = TRUE;
            }
        }
        else
        {
            DPrintf(0, ("%s - ERROR: add_buf failed", __FUNCTION__));
        }
    }
    else
    {
        DPrintf(0, ("%s (buffer %d,%d) - ERROR: message too LARGE", __FUNCTION__, size1, size2));
    }
    NdisReleaseSpinLock(&pContext->ReceiveLock);
    return bOK;
}

static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext)
{
    u8 val;
    ULONG f = pContext->PacketFilter;
    val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0;
    SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2);
    //SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2);
    val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1;
    SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2);
    val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1;
    SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2);
    val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1;
    SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2);
    val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0;
    SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2);
}

static VOID ParaNdis_DeviceFiltersUpdateAddresses(PARANDIS_ADAPTER *pContext)
{
    struct
    {
        struct virtio_net_ctrl_mac header;
        UCHAR addr[ETH_LENGTH_OF_ADDRESS];
    } uCast;
    uCast.header.entries = 1;
    NdisMoveMemory(uCast.addr, pContext->CurrentMacAddress, sizeof(uCast.addr));
    SendControlMessage(pContext, VIRTIO_NET_CTRL_MAC, VIRTIO_NET_CTRL_MAC_TABLE_SET,
        &uCast, sizeof(uCast), &pContext->MulticastData,sizeof(pContext->MulticastData.nofMulticastEntries) + pContext->MulticastData.nofMulticastEntries * ETH_ALEN, 2);
}

static VOID SetSingleVlanFilter(PARANDIS_ADAPTER *pContext, ULONG vlanId, BOOLEAN bOn, int levelIfOK)
{
    u16 val = vlanId & 0xfff;
    UCHAR cmd = bOn ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
    SendControlMessage(pContext, VIRTIO_NET_CTRL_VLAN, cmd, &val, sizeof(val), NULL, 0, levelIfOK);
}

static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn)
{
    ULONG i;
    for (i = 0; i <= MAX_VLAN_ID; ++i)
        SetSingleVlanFilter(pContext, i, bOn, 7);
}

/*
    possible values of filter set (pContext->ulCurrentVlansFilterSet):
    0 - all disabled
    1..4095 - one selected enabled
    4096 - all enabled
    Note that only 0th vlan can't be enabled
*/
VOID ParaNdis_DeviceFiltersUpdateVlanId(PARANDIS_ADAPTER *pContext)
{
    if (pContext->bHasHardwareFilters)
    {
        ULONG newFilterSet;
        if (IsVlanSupported(pContext))
            newFilterSet = pContext->VlanId ? pContext->VlanId : (MAX_VLAN_ID + 1);
        else
            newFilterSet = IsPrioritySupported(pContext) ? (MAX_VLAN_ID + 1) : 0;
        if (newFilterSet != pContext->ulCurrentVlansFilterSet)
        {
            if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
                SetAllVlanFilters(pContext, FALSE);
            else if (pContext->ulCurrentVlansFilterSet)
                SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, FALSE, 2);

            pContext->ulCurrentVlansFilterSet = newFilterSet;

            if (pContext->ulCurrentVlansFilterSet > MAX_VLAN_ID)
                SetAllVlanFilters(pContext, TRUE);
            else if (pContext->ulCurrentVlansFilterSet)
                SetSingleVlanFilter(pContext, pContext->ulCurrentVlansFilterSet, TRUE, 2);
        }
    }
}

VOID ParaNdis_UpdateDeviceFilters(PARANDIS_ADAPTER *pContext)
{
    if (pContext->bHasHardwareFilters)
    {
        ParaNdis_DeviceFiltersUpdateRxMode(pContext);
        ParaNdis_DeviceFiltersUpdateAddresses(pContext);
        ParaNdis_DeviceFiltersUpdateVlanId(pContext);
    }
}

NDIS_STATUS ParaNdis_PowerOn(PARANDIS_ADAPTER *pContext)
{
    LIST_ENTRY TempList;
    NDIS_STATUS status;
    DEBUG_ENTRY(0);
    ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 1, 0, 0);
    ParaNdis_ResetVirtIONetDevice(pContext);
    virtio_add_status(&pContext->IODevice, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER);
    /* virtio_get_features must be called once upon device initialization:
     otherwise the device will not work properly */
    (void)virtio_get_features(&pContext->IODevice);

    if (pContext->bUseMergedBuffers)
        VirtIODeviceEnableGuestFeature(pContext, VIRTIO_NET_F_MRG_RXBUF);
    if (VirtIODeviceGetHostFeature(pContext, VIRTIO_RING_F_EVENT_IDX))
        VirtIODeviceEnableGuestFeature(pContext, VIRTIO_RING_F_EVENT_IDX);
    if (pContext->bDoGuestChecksumOnReceive)
        VirtIODeviceEnableGuestFeature(pContext, VIRTIO_NET_F_GUEST_CSUM);
    if (VirtIODeviceGetHostFeature(pContext, VIRTIO_F_VERSION_1))
        VirtIODeviceEnableGuestFeature(pContext, VIRTIO_F_VERSION_1);
    if (VirtIODeviceGetHostFeature(pContext, VIRTIO_F_ANY_LAYOUT))
        VirtIODeviceEnableGuestFeature(pContext, VIRTIO_F_ANY_LAYOUT);

    status = FinalizeFeatures(pContext);
    if (status == NDIS_STATUS_SUCCESS) {
        status = FindNetQueues(pContext);
    }
    if (status != NDIS_STATUS_SUCCESS) {
        virtio_add_status(&pContext->IODevice, VIRTIO_CONFIG_S_FAILED);
        return status;
    }

    ParaNdis_RestoreDeviceConfigurationAfterReset(pContext);

    ParaNdis_UpdateDeviceFilters(pContext);

    InitializeListHead(&TempList);
    
    /* submit all the receive buffers */
    NdisAcquireSpinLock(&pContext->ReceiveLock);
    
    pContext->ReuseBufferProc = (tReuseReceiveBufferProc)ReuseReceiveBufferRegular;
    
    while (!IsListEmpty(&pContext->NetReceiveBuffers))
    {
        pIONetDescriptor pBufferDescriptor =
            (pIONetDescriptor)RemoveHeadList(&pContext->NetReceiveBuffers);
        InsertTailList(&TempList, &pBufferDescriptor->listEntry);
    }
    pContext->NetNofReceiveBuffers = 0;
    while (!IsListEmpty(&TempList))
    {
        pIONetDescriptor pBufferDescriptor =
            (pIONetDescriptor)RemoveHeadList(&TempList);
        if (AddRxBufferToQueue(pContext, pBufferDescriptor))
        {
            InsertTailList(&pContext->NetReceiveBuffers, &pBufferDescriptor->listEntry);
            pContext->NetNofReceiveBuffers++;
        }
        else
        {
            DPrintf(0, ("FAILED TO REUSE THE BUFFER!!!!"));
            VirtIONetFreeBufferDescriptor(pContext, pBufferDescriptor);
            pContext->NetMaxReceiveBuffers--;
        }
    }
    virtqueue_kick(pContext->NetReceiveQueue);
    ParaNdis_SetPowerState(pContext, NdisDeviceStateD0);
    pContext->bEnableInterruptHandlingDPC = TRUE;
    virtio_device_ready(&pContext->IODevice);
    
    NdisReleaseSpinLock(&pContext->ReceiveLock);

    // if bFastSuspendInProcess is set by Win8 power-off procedure,
    // the ParaNdis_Resume enables Tx and RX
    // otherwise it does not do anything in Vista+ (Tx and RX are enabled after power-on by Restart)
    ParaNdis_Resume(pContext);
    pContext->bFastSuspendInProcess = FALSE;
    
    ParaNdis_ReportLinkStatus(pContext, TRUE);
    ParaNdis_DebugHistory(pContext, hopPowerOn, NULL, 0, 0, 0);

    return status;
}

VOID ParaNdis_PowerOff(PARANDIS_ADAPTER *pContext)
{
    DEBUG_ENTRY(0);
    ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 1, 0, 0);

    ParaNdis_IndicateConnect(pContext, FALSE, FALSE);

    // if bFastSuspendInProcess is set by Win8 power-off procedure
    // the ParaNdis_Suspend does fast Rx stop without waiting (=>srsPausing, if there are some RX packets in Ndis)
    pContext->bFastSuspendInProcess = pContext->bNoPauseOnSuspend && pContext->ReceiveState == srsEnabled;
    ParaNdis_Suspend(pContext);
    if (pContext->IODevice.addr)
    {
        /* back compat - remove the OK flag only in legacy mode */
        VirtIODeviceRemoveStatus(&pContext->IODevice, VIRTIO_CONFIG_S_DRIVER_OK);
    }
    
    if (pContext->bFastSuspendInProcess)
    {
        NdisAcquireSpinLock(&pContext->ReceiveLock);
        pContext->ReuseBufferProc = (tReuseReceiveBufferProc)ReuseReceiveBufferPowerOff;
        NdisReleaseSpinLock(&pContext->ReceiveLock);
    }
    
    ParaNdis_SetPowerState(pContext, NdisDeviceStateD3);

    PreventDPCServicing(pContext);

    /*******************************************************************
        shutdown queues to have all the receive buffers under our control
        all the transmit buffers move to list of free buffers
    ********************************************************************/

    NdisAcquireSpinLock(&pContext->SendLock);
    virtqueue_shutdown(pContext->NetSendQueue);
    while (!IsListEmpty(&pContext->NetSendBuffersInUse))
    {
        pIONetDescriptor pBufferDescriptor =
            (pIONetDescriptor)RemoveHeadList(&pContext->NetSendBuffersInUse);
        InsertTailList(&pContext->NetFreeSendBuffers, &pBufferDescriptor->listEntry);
        pContext->nofFreeTxDescriptors++;
        pContext->nofFreeHardwareBuffers += pBufferDescriptor->nofUsedBuffers;
    }
    NdisReleaseSpinLock(&pContext->SendLock);

    NdisAcquireSpinLock(&pContext->ReceiveLock);
    virtqueue_shutdown(pContext->NetReceiveQueue);
    NdisReleaseSpinLock(&pContext->ReceiveLock);
    if (pContext->NetControlQueue) {
        virtqueue_shutdown(pContext->NetControlQueue);
    }

    DPrintf(0, ("WARNING: deleting queues!!!!!!!!!"));
    DeleteNetQueues(pContext);
    pContext->NetSendQueue = NULL;
    pContext->NetReceiveQueue = NULL;
    pContext->NetControlQueue = NULL;

    ParaNdis_ResetVirtIONetDevice(pContext);
    ParaNdis_DebugHistory(pContext, hopPowerOff, NULL, 0, 0, 0);
}

void ParaNdis_CallOnBugCheck(PARANDIS_ADAPTER *pContext)
{
    if (pContext->IODevice.isr)
    {
#ifdef DBG_USE_VIRTIO_PCI_ISR_FOR_HOST_REPORT
        WriteVirtIODeviceByte(pContext->IODevice.isr, 1);
#endif
    }
}

tChecksumCheckResult ParaNdis_CheckRxChecksum(PARANDIS_ADAPTER *pContext, ULONG virtioFlags, PVOID pRxPacket, ULONG len)
{
    tOffloadSettingsFlags f = pContext->Offload.flags;
    tChecksumCheckResult res, resIp;
    PVOID pIpHeader = RtlOffsetToPointer(pRxPacket, ETH_HEADER_SIZE);
    tTcpIpPacketParsingResult ppr;
    ULONG flagsToCalculate = 0;
    res.value = 0;
    resIp.value = 0;

    //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS
    //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK

    if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only

    if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
    {
        if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
        {
            flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
        }
        else
        {
            if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
            if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
            if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
            if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
        }
    }

    ppr = ParaNdis_CheckSumVerify(pIpHeader, len - ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);

    if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
    {
        pContext->extraStatistics.framesRxCSHwOK++;
        ppr.xxpCheckSum = ppresCSOK;
    }

    if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
    {
        if (f.fRxIPChecksum)
        {
            res.flags.IpOK =  ppr.ipCheckSum == ppresCSOK;
            res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
        }
        if(ppr.xxpStatus == ppresXxpKnown)
        {
            if(ppr.TcpUdp == ppresIsTCP) /* TCP */
            {
                if (f.fRxTCPChecksum)
                {
                    res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
                    res.flags.TcpFailed = !res.flags.TcpOK;
                }
            }
            else /* UDP */
            {
                if (f.fRxUDPChecksum)
                {
                    res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
                    res.flags.UdpFailed = !res.flags.UdpOK;
                }
            }
        }
    }
    else if (ppr.ipStatus == ppresIPV6)
    {
        if(ppr.xxpStatus == ppresXxpKnown)
        {
            if(ppr.TcpUdp == ppresIsTCP) /* TCP */
            {
                if (f.fRxTCPv6Checksum)
                {
                    res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
                    res.flags.TcpFailed = !res.flags.TcpOK;
                }
            }
            else /* UDP */
            {
                if (f.fRxUDPv6Checksum)
                {
                    res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
                    res.flags.UdpFailed = !res.flags.UdpOK;
                }
            }
        }
    }

    if (pContext->bDoIPCheckRx &&
        (f.fRxIPChecksum || f.fRxTCPChecksum || f.fRxUDPChecksum || f.fRxTCPv6Checksum || f.fRxUDPv6Checksum))
    {
        ppr = ParaNdis_CheckSumVerify(pIpHeader, len - ETH_HEADER_SIZE, pcrAnyChecksum, __FUNCTION__);
        if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
        {
            resIp.flags.IpOK = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSOK;
            resIp.flags.IpFailed = !!f.fRxIPChecksum && ppr.ipCheckSum == ppresCSBad;
            if (f.fRxTCPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP)
            {
                resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK;
                resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad;
            }
            if (f.fRxUDPChecksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP)
            {
                resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK;
                resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad;
            }
        }
        else if (ppr.ipStatus == ppresIPV6)
        {
            if (f.fRxTCPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsTCP)
            {
                resIp.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK;
                resIp.flags.TcpFailed = ppr.xxpCheckSum == ppresCSBad;
            }
            if (f.fRxUDPv6Checksum && ppr.xxpStatus == ppresXxpKnown && ppr.TcpUdp == ppresIsUDP)
            {
                resIp.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK;
                resIp.flags.UdpFailed = ppr.xxpCheckSum == ppresCSBad;
            }
        }

        if (res.value != resIp.value)
        {
            // if HW did not set some bits that IP checker set, it is a mistake:
            // or GOOD CS is not labeled, or BAD checksum is not labeled
            tChecksumCheckResult diff;
            diff.value = resIp.value & ~res.value;
            if (diff.flags.IpFailed || diff.flags.TcpFailed || diff.flags.UdpFailed)
                pContext->extraStatistics.framesRxCSHwMissedBad++;
            if (diff.flags.IpOK || diff.flags.TcpOK || diff.flags.UdpOK)
                pContext->extraStatistics.framesRxCSHwMissedGood++;
            if (diff.value)
            {
                DPrintf(0, ("[%s] real %X <> %X (virtio %X)", __FUNCTION__, resIp.value, res.value, virtioFlags));
            }
            res.value = resIp.value;
        }
    }

    return res;
}