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

#include "precomp.h"

#include "Actions.h"
#include "Conntrack.h"
#include "Debug.h"
#include "Event.h"
#include "Flow.h"
#include "Gre.h"
#include "Jhash.h"
#include "Meter.h"
#include "Mpls.h"
#include "NetProto.h"
#include "Offload.h"
#include "PacketIO.h"
#include "Recirc.h"
#include "Stt.h"
#include "Switch.h"
#include "User.h"
#include "Vport.h"
#include "Vxlan.h"
#include "Geneve.h"
#include "IpFragment.h"

#ifdef OVS_DBG_MOD
#undef OVS_DBG_MOD
#endif
#define OVS_DBG_MOD OVS_DBG_ACTION

#define OVS_DEST_PORTS_ARRAY_MIN_SIZE 2

typedef struct _OVS_ACTION_STATS {
    UINT64 rxGre;
    UINT64 txGre;
    UINT64 rxVxlan;
    UINT64 txVxlan;
    UINT64 rxStt;
    UINT64 txStt;
    UINT64 rxGeneve;
    UINT64 txGeneve;
    UINT64 flowMiss;
    UINT64 flowUserspace;
    UINT64 txTcp;
    UINT32 failedFlowMiss;
    UINT32 noVport;
    UINT32 failedFlowExtract;
    UINT32 noResource;
    UINT32 noCopiedNbl;
    UINT32 failedEncap;
    UINT32 failedDecap;
    UINT32 cannotGrowDest;
    UINT32 zeroActionLen;
    UINT32 failedChecksum;
    UINT32 deferredActionsQueueFull;
    UINT32 deferredActionsExecLimit;
} OVS_ACTION_STATS, *POVS_ACTION_STATS;

OVS_ACTION_STATS ovsActionStats;

/*
 * --------------------------------------------------------------------------
 * OvsInitForwardingCtx --
 *     Function to init/re-init the 'ovsFwdCtx' context as the actions pipeline
 *     is being executed.
 *
 * Result:
 *     NDIS_STATUS_SUCCESS on success
 *     Other NDIS_STATUS upon failure. Upon failure, it is safe to call
 *     OvsCompleteNBLForwardingCtx(), since 'ovsFwdCtx' has been initialized
 *     enough for OvsCompleteNBLForwardingCtx() to do its work.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsInitForwardingCtx(OvsForwardingContext *ovsFwdCtx,
                     POVS_SWITCH_CONTEXT switchContext,
                     PNET_BUFFER_LIST curNbl,
                     UINT32 srcVportNo,
                     ULONG sendFlags,
                     PNDIS_SWITCH_FORWARDING_DETAIL_NET_BUFFER_LIST_INFO fwdDetail,
                     OvsCompletionList *completionList,
                     OVS_PACKET_HDR_INFO *layers,
                     BOOLEAN resetTunnelInfo)
{
    ASSERT(ovsFwdCtx);
    ASSERT(switchContext);
    ASSERT(curNbl);
    ASSERT(fwdDetail);

    /*
     * Set values for curNbl and switchContext so upon failures, we have enough
     * information to do cleanup.
     */
    ovsFwdCtx->curNbl = curNbl;
    ovsFwdCtx->switchContext = switchContext;
    ovsFwdCtx->completionList = completionList;
    ovsFwdCtx->fwdDetail = fwdDetail;

    if (fwdDetail->NumAvailableDestinations > 0) {
        /*
         * XXX: even though MSDN says GetNetBufferListDestinations() returns
         * NDIS_STATUS, the header files say otherwise.
         */
        switchContext->NdisSwitchHandlers.GetNetBufferListDestinations(
            switchContext->NdisSwitchContext, curNbl,
            &ovsFwdCtx->destinationPorts);

        ASSERT(ovsFwdCtx->destinationPorts);
        /* Ensure that none of the elements are consumed yet. */
        ASSERT(ovsFwdCtx->destinationPorts->NumElements ==
               fwdDetail->NumAvailableDestinations);
    } else {
        ovsFwdCtx->destinationPorts = NULL;
    }
    ovsFwdCtx->destPortsSizeIn = fwdDetail->NumAvailableDestinations;
    ovsFwdCtx->destPortsSizeOut = 0;
    ovsFwdCtx->srcVportNo = srcVportNo;
    ovsFwdCtx->sendFlags = sendFlags;
    if (layers) {
        ovsFwdCtx->layers = *layers;
    } else {
        RtlZeroMemory(&ovsFwdCtx->layers, sizeof ovsFwdCtx->layers);
    }
    if (resetTunnelInfo) {
        ovsFwdCtx->tunnelTxNic = NULL;
        ovsFwdCtx->tunnelRxNic = NULL;
        RtlZeroMemory(&ovsFwdCtx->tunKey, sizeof ovsFwdCtx->tunKey);
    }

    return NDIS_STATUS_SUCCESS;
}

/*
 * --------------------------------------------------------------------------
 * OvsDoFragmentNbl --
 *     Utility function to Fragment nbl based on mru.
 * --------------------------------------------------------------------------
 */
static __inline VOID
OvsDoFragmentNbl(OvsForwardingContext *ovsFwdCtx, UINT16 mru)
{
    PNET_BUFFER_LIST fragNbl = NULL;
    fragNbl = OvsFragmentNBL(ovsFwdCtx->switchContext,
                             ovsFwdCtx->curNbl,
                             &(ovsFwdCtx->layers),
                             mru, 0, TRUE);

   if (fragNbl != NULL) {
        OvsCompleteNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl, TRUE);
        ovsFwdCtx->curNbl = fragNbl;
    } else {
        OVS_LOG_INFO("Fragment NBL failed for MRU = %u", mru);
    }
}

/*
 * --------------------------------------------------------------------------
 * OvsDetectTunnelRxPkt --
 *     Utility function for an RX packet to detect its tunnel type.
 *
 * Result:
 *  True  - if the tunnel type was detected.
 *  False - if not a tunnel packet or tunnel type not supported.
 * --------------------------------------------------------------------------
 */
static __inline BOOLEAN
OvsDetectTunnelRxPkt(OvsForwardingContext *ovsFwdCtx,
                     const OvsFlowKey *flowKey)
{
    POVS_VPORT_ENTRY tunnelVport = NULL;

    /* XXX: we should also check for the length of the UDP payload to pick
     * packets only if they are at least VXLAN header size.
     */

     /*
      * For some of the tunnel types such as GRE, the dstPort is not applicable
      * since GRE does not have a L4 port. We use '0' for convenience.
      */

    if ((flowKey->l2.dlType == htons(ETH_TYPE_IPV4) &&
        !flowKey->ipKey.nwFrag) ||
        (flowKey->l2.dlType == htons(ETH_TYPE_IPV6) &&
        !flowKey->ipv6Key.nwFrag)) {
        UINT16 dstPort = 0;
        uint8_t nwProto = 0;
        if (flowKey->l2.dlType == htons(ETH_TYPE_IPV6)) {
            dstPort = htons(flowKey->ipv6Key.l4.tpDst);
            nwProto = flowKey->ipv6Key.nwProto;
         } else if (flowKey->l2.dlType == htons(ETH_TYPE_IPV4)) {
            dstPort = htons(flowKey->ipKey.l4.tpDst);
            nwProto = flowKey->ipKey.nwProto;
        }
        ASSERT(nwProto != IPPROTO_GRE || dstPort == 0);

        tunnelVport =
            OvsFindTunnelVportByDstPortAndNWProto(ovsFwdCtx->switchContext,
                                                  dstPort, nwProto);
        if (tunnelVport) {
            switch(tunnelVport->ovsType) {
            case OVS_VPORT_TYPE_STT:
                ovsActionStats.rxStt++;
                break;
            case OVS_VPORT_TYPE_VXLAN:
                ovsActionStats.rxVxlan++;
                break;
            case OVS_VPORT_TYPE_GENEVE:
                ovsActionStats.rxGeneve++;
                break;
            case OVS_VPORT_TYPE_GRE:
                ovsActionStats.rxGre++;
                break;
            }
        }
    }

    // We might get tunnel packets even before the tunnel gets initialized.
    if (tunnelVport) {
        ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
        ovsFwdCtx->tunnelRxNic = tunnelVport;
        return TRUE;
    }

    return FALSE;
}

/*
 * --------------------------------------------------------------------------
 * OvsDetectTunnelPkt --
 *     Utility function to detect if a packet is to be subjected to
 *     tunneling (Tx) or de-tunneling (Rx). Various factors such as source
 *     port, destination port, packet contents, and previously setup tunnel
 *     context are used.
 *
 * Result:
 *  True  - If the packet is to be subjected to tunneling.
 *          In case of invalid tunnel context, the tunneling functionality is
 *          a no-op and is completed within this function itself by consuming
 *          all of the tunneling context.
 *  False - If not a tunnel packet or tunnel type not supported. Caller should
 *          process the packet as a non-tunnel packet.
 * --------------------------------------------------------------------------
 */
static __inline BOOLEAN
OvsDetectTunnelPkt(OvsForwardingContext *ovsFwdCtx,
                   const POVS_VPORT_ENTRY dstVport,
                   const OvsFlowKey *flowKey)
{
    if (OvsIsInternalVportType(dstVport->ovsType)) {
        /*
         * Rx:
         * The source of NBL during tunneling Rx could be the external
         * port or if it is being executed from userspace, the source port is
         * default port.
         */
        BOOLEAN validSrcPort =
            (OvsIsExternalVportByPortId(ovsFwdCtx->switchContext,
                 ovsFwdCtx->fwdDetail->SourcePortId)) ||
            (ovsFwdCtx->fwdDetail->SourcePortId ==
                 NDIS_SWITCH_DEFAULT_PORT_ID);

        if (validSrcPort && OvsDetectTunnelRxPkt(ovsFwdCtx, flowKey)) {
            ASSERT(ovsFwdCtx->tunnelTxNic == NULL);
            ASSERT(ovsFwdCtx->tunnelRxNic != NULL);
            return TRUE;
        }
    } else if (OvsIsTunnelVportType(dstVport->ovsType)) {
        ASSERT(ovsFwdCtx->tunnelRxNic == NULL);

        /*
         * Tx:
         * The destination port is a tunnel port. Encapsulation must be
         * performed only on packets that originate from:
         * - a VIF port
         * - a bridge-internal port (packets generated from userspace)
         * - no port.
         * - tunnel port
         * If the packet will not be encapsulated, consume the tunnel context
         * by clearing it.
         */
        if (ovsFwdCtx->srcVportNo != OVS_DPPORT_NUMBER_INVALID) {

            POVS_VPORT_ENTRY vport = OvsFindVportByPortNo(
                ovsFwdCtx->switchContext, ovsFwdCtx->srcVportNo);

            if (!vport ||
                (vport->ovsType != OVS_VPORT_TYPE_NETDEV &&
                 vport->ovsType != OVS_VPORT_TYPE_INTERNAL &&
                 !OvsIsTunnelVportType(vport->ovsType))) {
                RtlZeroMemory(&ovsFwdCtx->tunKey.dst, sizeof(ovsFwdCtx->tunKey.dst));
            }
        }

        /* Tunnel the packet only if tunnel context is set. */
        if (!OvsIphIsZero(&(ovsFwdCtx->tunKey.dst))) {
            switch(dstVport->ovsType) {
            case OVS_VPORT_TYPE_GRE:
                ovsActionStats.txGre++;
                break;
            case OVS_VPORT_TYPE_VXLAN:
                ovsActionStats.txVxlan++;
                break;
            case OVS_VPORT_TYPE_STT:
                ovsActionStats.txStt++;
                break;
            case OVS_VPORT_TYPE_GENEVE:
               ovsActionStats.txGeneve++;
               break;
            }
            ovsFwdCtx->tunnelTxNic = dstVport;
        }

        return TRUE;
    }

    return FALSE;
}


/*
 * --------------------------------------------------------------------------
 * OvsAddPorts --
 *     Add the specified destination vport into the forwarding context. If the
 *     vport is a VIF/external port, it is added directly to the NBL. If it is
 *     a tunneling port, it is NOT added to the NBL.
 *
 * Result:
 *     NDIS_STATUS_SUCCESS on success
 *     Other NDIS_STATUS upon failure.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsAddPorts(OvsForwardingContext *ovsFwdCtx,
            OvsFlowKey *flowKey,
            NDIS_SWITCH_PORT_ID dstPortId,
            BOOLEAN preserveVLAN,
            BOOLEAN preservePriority)
{
    POVS_VPORT_ENTRY vport;
    PNDIS_SWITCH_PORT_DESTINATION fwdPort;
    NDIS_STATUS status;
    POVS_SWITCH_CONTEXT switchContext = ovsFwdCtx->switchContext;

    /*
     * We hold the dispatch lock that protects the list of vports, so vports
     * validated here can be added as destinations safely before we call into
     * NDIS.
     *
     * Some of the vports can be tunnelled ports as well in which case
     * they should be added to a separate list of tunnelled destination ports
     * instead of the VIF ports. The context for the tunnel is settable
     * in OvsForwardingContext.
     */
    vport = OvsFindVportByPortNo(ovsFwdCtx->switchContext, dstPortId);
    if (vport == NULL || vport->ovsState != OVS_STATE_CONNECTED) {
        /*
         * There may be some latency between a port disappearing, and userspace
         * updating the recalculated flows. In the meantime, handle invalid
         * ports gracefully.
         */
        ovsActionStats.noVport++;
        return NDIS_STATUS_SUCCESS;
    }
    ASSERT(vport->nicState == NdisSwitchNicStateConnected);
    vport->stats.txPackets++;
    vport->stats.txBytes +=
        NET_BUFFER_DATA_LENGTH(NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl));

    if (OvsDetectTunnelPkt(ovsFwdCtx, vport, flowKey)) {
        return NDIS_STATUS_SUCCESS;
    }

    if (ovsFwdCtx->destPortsSizeOut == ovsFwdCtx->destPortsSizeIn) {
        if (ovsFwdCtx->destPortsSizeIn == 0) {
            ASSERT(ovsFwdCtx->destinationPorts == NULL);
            ASSERT(ovsFwdCtx->fwdDetail->NumAvailableDestinations == 0);
            status =
                switchContext->NdisSwitchHandlers.GrowNetBufferListDestinations(
                    switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
                    OVS_DEST_PORTS_ARRAY_MIN_SIZE,
                    &ovsFwdCtx->destinationPorts);
            if (status != NDIS_STATUS_SUCCESS) {
                ovsActionStats.cannotGrowDest++;
                return status;
            }
            ovsFwdCtx->destPortsSizeIn =
                ovsFwdCtx->fwdDetail->NumAvailableDestinations;
            ASSERT(ovsFwdCtx->destinationPorts);
        } else {
            ASSERT(ovsFwdCtx->destinationPorts != NULL);
            /*
             * NumElements:
             * A ULONG value that specifies the total number of
             * NDIS_SWITCH_PORT_DESTINATION elements in the
             * NDIS_SWITCH_FORWARDING_DESTINATION_ARRAY structure.
             *
             * NumDestinations:
             * A ULONG value that specifies the number of
             * NDIS_SWITCH_PORT_DESTINATION elements in the
             * NDIS_SWITCH_FORWARDING_DESTINATION_ARRAY structure that
             * specify port destinations.
             *
             * NumAvailableDestinations:
             * A value that specifies the number of unused extensible switch
             * destination ports elements within an NET_BUFFER_LIST structure.
             */
            ASSERT(ovsFwdCtx->destinationPorts->NumElements ==
                   ovsFwdCtx->destPortsSizeIn);
            ASSERT(ovsFwdCtx->destinationPorts->NumDestinations ==
                   ovsFwdCtx->destPortsSizeOut -
                   ovsFwdCtx->fwdDetail->NumAvailableDestinations);
            ASSERT(ovsFwdCtx->fwdDetail->NumAvailableDestinations > 0);
            /*
             * Before we grow the array of destination ports, the current set
             * of ports needs to be committed. Only the ports added since the
             * last commit need to be part of the new update.
             */
            status = switchContext->NdisSwitchHandlers.UpdateNetBufferListDestinations(
                switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
                ovsFwdCtx->fwdDetail->NumAvailableDestinations,
                ovsFwdCtx->destinationPorts);
            if (status != NDIS_STATUS_SUCCESS) {
                ovsActionStats.cannotGrowDest++;
                return status;
            }
            ASSERT(ovsFwdCtx->destinationPorts->NumElements ==
                   ovsFwdCtx->destPortsSizeIn);
            ASSERT(ovsFwdCtx->destinationPorts->NumDestinations ==
                   ovsFwdCtx->destPortsSizeOut);
            ASSERT(ovsFwdCtx->fwdDetail->NumAvailableDestinations == 0);

            status = switchContext->NdisSwitchHandlers.GrowNetBufferListDestinations(
                switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
                ovsFwdCtx->destPortsSizeIn, &ovsFwdCtx->destinationPorts);
            if (status != NDIS_STATUS_SUCCESS) {
                ovsActionStats.cannotGrowDest++;
                return status;
            }
            ASSERT(ovsFwdCtx->destinationPorts != NULL);
            ovsFwdCtx->destPortsSizeIn <<= 1;
        }
    }

    ASSERT(ovsFwdCtx->destPortsSizeOut < ovsFwdCtx->destPortsSizeIn);
    fwdPort =
        NDIS_SWITCH_PORT_DESTINATION_AT_ARRAY_INDEX(ovsFwdCtx->destinationPorts,
                                                    ovsFwdCtx->destPortsSizeOut);

    fwdPort->PortId = vport->portId;
    fwdPort->NicIndex = vport->nicIndex;
    fwdPort->IsExcluded = 0;
    fwdPort->PreserveVLAN = preserveVLAN;
    fwdPort->PreservePriority = preservePriority;
    ovsFwdCtx->destPortsSizeOut += 1;

    return NDIS_STATUS_SUCCESS;
}


/*
 * --------------------------------------------------------------------------
 * OvsClearTunTxCtx --
 *     Utility function to clear tx tunneling context.
 * --------------------------------------------------------------------------
 */
static __inline VOID
OvsClearTunTxCtx(OvsForwardingContext *ovsFwdCtx)
{
    ovsFwdCtx->tunnelTxNic = NULL;
    RtlZeroMemory(&ovsFwdCtx->tunKey.dst, sizeof(ovsFwdCtx->tunKey.dst));
}


/*
 * --------------------------------------------------------------------------
 * OvsClearTunRxCtx --
 *     Utility function to clear rx tunneling context.
 * --------------------------------------------------------------------------
 */
static __inline VOID
OvsClearTunRxCtx(OvsForwardingContext *ovsFwdCtx)
{
    ovsFwdCtx->tunnelRxNic = NULL;
    RtlZeroMemory(&ovsFwdCtx->tunKey.dst, sizeof(ovsFwdCtx->tunKey.dst));
}


/*
 * --------------------------------------------------------------------------
 * OvsCompleteNBLForwardingCtx --
 *     This utility function is responsible for freeing/completing an NBL - either
 *     by adding it to a completion list or by freeing it.
 *
 * Side effects:
 *     It also resets the necessary fields in 'ovsFwdCtx'.
 * --------------------------------------------------------------------------
 */
static __inline VOID
OvsCompleteNBLForwardingCtx(OvsForwardingContext *ovsFwdCtx,
                            PCWSTR dropReason)
{
    NDIS_STRING filterReason;

    RtlInitUnicodeString(&filterReason, dropReason);
    if (ovsFwdCtx->completionList) {
        OvsAddPktCompletionList(ovsFwdCtx->completionList, TRUE,
            ovsFwdCtx->fwdDetail->SourcePortId, ovsFwdCtx->curNbl, 1,
            &filterReason);
        ovsFwdCtx->curNbl = NULL;
    } else {
        /* If there is no completionList, we assume this is ovs created NBL */
        ovsFwdCtx->curNbl = OvsCompleteNBL(ovsFwdCtx->switchContext,
                                           ovsFwdCtx->curNbl, TRUE);
        ASSERT(ovsFwdCtx->curNbl == NULL);
    }
    /* XXX: these can be made debug only to save cycles. Ideally the pipeline
     * using these fields should reset the values at the end of the pipeline. */
    ovsFwdCtx->destPortsSizeOut = 0;
    ovsFwdCtx->tunnelTxNic = NULL;
    ovsFwdCtx->tunnelRxNic = NULL;
}

/*
 * --------------------------------------------------------------------------
 * OvsDoFlowLookupOutput --
 *     Function to be used for the second stage of a tunneling workflow, ie.:
 *     - On the encapsulated packet on Tx path, to do a flow extract, flow
 *       lookup and excuting the actions.
 *     - On the decapsulated packet on Rx path, to do a flow extract, flow
 *       lookup and excuting the actions.
 *
 *     XXX: It is assumed that the NBL in 'ovsFwdCtx' is owned by OVS. This is
 *     until the new buffer management framework is adopted.
 *
 * Side effects:
 *     The NBL in 'ovsFwdCtx' is consumed.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsDoFlowLookupOutput(OvsForwardingContext* ovsFwdCtx)
{
    OvsFlowKey key = { 0 };
    OvsFlow *flow = NULL;
    UINT64 hash = 0;
    NDIS_STATUS status = NDIS_STATUS_SUCCESS;
    POVS_VPORT_ENTRY vport =
        OvsFindVportByPortNo(ovsFwdCtx->switchContext, ovsFwdCtx->srcVportNo);
    if (vport == NULL || vport->ovsState != OVS_STATE_CONNECTED) {
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
            L"OVS-Dropped due to internal/tunnel port removal");
        ovsActionStats.noVport++;
        return NDIS_STATUS_SUCCESS;
    }
    ASSERT(vport->nicState == NdisSwitchNicStateConnected);

    /* Assert that in the Rx direction, key is always setup. */
    ASSERT(ovsFwdCtx->tunnelRxNic == NULL || !OvsIphIsZero(&(ovsFwdCtx->tunKey.dst)));
    status =
        OvsExtractFlow(ovsFwdCtx->curNbl, ovsFwdCtx->srcVportNo,
                       &key, &ovsFwdCtx->layers,
                       !OvsIphIsZero(&(ovsFwdCtx->tunKey.dst))? &(ovsFwdCtx->tunKey):NULL);
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                    L"OVS-Flow extract failed");
        ovsActionStats.failedFlowExtract++;
        return status;
    }

    flow = OvsLookupFlow(&ovsFwdCtx->switchContext->datapath, &key, &hash, FALSE);
    if (flow) {
        OvsFlowUsed(flow, ovsFwdCtx->curNbl, &ovsFwdCtx->layers);
        ovsFwdCtx->switchContext->datapath.hits++;
        status = OvsDoExecuteActions(ovsFwdCtx->switchContext,
                                     ovsFwdCtx->completionList,
                                     ovsFwdCtx->curNbl,
                                     ovsFwdCtx->srcVportNo,
                                     ovsFwdCtx->sendFlags,
                                     &key, &hash, &ovsFwdCtx->layers,
                                     flow->actions, flow->actionsLen);
        ovsFwdCtx->curNbl = NULL;
    } else {
        LIST_ENTRY missedPackets;
        UINT32 num = 0;
        ovsFwdCtx->switchContext->datapath.misses++;
        InitializeListHead(&missedPackets);
        status = OvsCreateAndAddPackets(NULL, 0, OVS_PACKET_CMD_MISS, vport,
                          &key,ovsFwdCtx->curNbl,
                          FALSE, &ovsFwdCtx->layers,
                          ovsFwdCtx->switchContext, &missedPackets, &num);
        if (num) {
            OvsQueuePackets(&missedPackets, num);
        }
        if (status == NDIS_STATUS_SUCCESS) {
            /* Complete the packet since it was copied to user buffer. */
            OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                L"OVS-Dropped since packet was copied to userspace");
            ovsActionStats.flowMiss++;
            status = NDIS_STATUS_SUCCESS;
        } else {
            OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                L"OVS-Dropped due to failure to queue to userspace");
            status = NDIS_STATUS_FAILURE;
            ovsActionStats.failedFlowMiss++;
        }
    }

    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsTunnelPortTx --
 *     The start function for Tx tunneling - encapsulates the packet, and
 *     outputs the packet on the PIF bridge.
 *
 * Side effects:
 *     The NBL in 'ovsFwdCtx' is consumed.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsTunnelPortTx(OvsForwardingContext *ovsFwdCtx)
{
    NDIS_STATUS status = NDIS_STATUS_FAILURE;
    PNET_BUFFER_LIST newNbl = NULL;
    UINT32 srcVportNo;
    NDIS_SWITCH_NIC_INDEX srcNicIndex;
    NDIS_SWITCH_PORT_ID srcPortId;
    POVS_BUFFER_CONTEXT ctx;

    /*
     * Setup the source port to be the internal port to as to facilitate the
     * second OvsLookupFlow.
     */
    if (ovsFwdCtx->switchContext->countInternalVports <= 0 ||
        ovsFwdCtx->switchContext->virtualExternalVport == NULL) {
        OvsClearTunTxCtx(ovsFwdCtx);
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
            L"OVS-Dropped since either internal or external port is absent");
        return NDIS_STATUS_FAILURE;
    }

    ctx = (POVS_BUFFER_CONTEXT)NET_BUFFER_LIST_CONTEXT_DATA_START(ovsFwdCtx->curNbl);
    if (ctx->mru != 0) {
        OvsDoFragmentNbl(ovsFwdCtx, ctx->mru);
    }
    OVS_FWD_INFO switchFwdInfo = { 0 };

    /* Apply the encapsulation. The encapsulation will not consume the NBL. */
    switch(ovsFwdCtx->tunnelTxNic->ovsType) {
    case OVS_VPORT_TYPE_GRE:
        status = OvsEncapGre(ovsFwdCtx->tunnelTxNic, ovsFwdCtx->curNbl,
                             &ovsFwdCtx->tunKey, ovsFwdCtx->switchContext,
                             &ovsFwdCtx->layers, &newNbl, &switchFwdInfo);
        break;
    case OVS_VPORT_TYPE_VXLAN:
        status = OvsEncapVxlan(ovsFwdCtx->tunnelTxNic, ovsFwdCtx->curNbl,
                               &ovsFwdCtx->tunKey, ovsFwdCtx->switchContext,
                               &ovsFwdCtx->layers, &newNbl, &switchFwdInfo);
        break;
    case OVS_VPORT_TYPE_STT:
        status = OvsEncapStt(ovsFwdCtx->tunnelTxNic, ovsFwdCtx->curNbl,
                             &ovsFwdCtx->tunKey, ovsFwdCtx->switchContext,
                             &ovsFwdCtx->layers, &newNbl, &switchFwdInfo);
        break;
    case OVS_VPORT_TYPE_GENEVE:
        status = OvsEncapGeneve(ovsFwdCtx->tunnelTxNic, ovsFwdCtx->curNbl,
                                &ovsFwdCtx->tunKey, ovsFwdCtx->switchContext,
                                &ovsFwdCtx->layers, &newNbl, &switchFwdInfo);
        break;
    default:
        ASSERT(! "Tx: Unhandled tunnel type");
    }

    /* Reset the tunnel context so that it doesn't get used after this point. */
    OvsClearTunTxCtx(ovsFwdCtx);

    if (status == NDIS_STATUS_SUCCESS && switchFwdInfo.vport != NULL) {
        ASSERT(newNbl);
        /*
         * Save the 'srcVportNo', 'srcPortId', 'srcNicIndex' so that
         * this can be applied to the new NBL later on.
         */
        srcVportNo = switchFwdInfo.vport->portNo;
        srcPortId = switchFwdInfo.vport->portId;
        srcNicIndex = switchFwdInfo.vport->nicIndex;

        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                    L"Complete after cloning NBL for encapsulation");
        status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
                                      newNbl, srcVportNo, 0,
                                      NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                                      ovsFwdCtx->completionList,
                                      &ovsFwdCtx->layers, FALSE);
        ovsFwdCtx->curNbl = newNbl;
        /* Update the forwarding detail for the new NBL */
        ovsFwdCtx->fwdDetail->SourcePortId = srcPortId;
        ovsFwdCtx->fwdDetail->SourceNicIndex = srcNicIndex;
        status = OvsDoFlowLookupOutput(ovsFwdCtx);
        ASSERT(ovsFwdCtx->curNbl == NULL);
    } else {
        /*
         * XXX: Temporary freeing of the packet until we register a
         * callback to IP helper.
         */
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                    L"OVS-Dropped due to encap failure");
        ovsActionStats.failedEncap++;
        status = NDIS_STATUS_SUCCESS;
    }

    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsTunnelPortRx --
 *     Decapsulate the incoming NBL based on the tunnel type and goes through
 *     the flow lookup for the inner packet.
 *
 *     Note: IP checksum is validate here, but L4 checksum validation needs
 *     to be done by the corresponding tunnel types.
 *
 * Side effects:
 *     The NBL in 'ovsFwdCtx' is consumed.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsTunnelPortRx(OvsForwardingContext *ovsFwdCtx)
{
    NDIS_STATUS status = NDIS_STATUS_SUCCESS;
    PNET_BUFFER_LIST newNbl = NULL;
    POVS_VPORT_ENTRY tunnelRxVport = ovsFwdCtx->tunnelRxNic;
    PCWSTR dropReason = L"OVS-dropped due to new decap packet";

    if (OvsValidateIPChecksum(ovsFwdCtx->curNbl, &ovsFwdCtx->layers)
            != NDIS_STATUS_SUCCESS) {
        ovsActionStats.failedChecksum++;
        OVS_LOG_INFO("Packet dropped due to IP checksum failure.");
        goto dropNbl;
    }

    /*
     * Decap port functions should return a new NBL if it was copied, and
     * this new NBL should be setup as the ovsFwdCtx->curNbl.
     */

    switch(tunnelRxVport->ovsType) {
    case OVS_VPORT_TYPE_GRE:
        status = OvsDecapGre(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                             &ovsFwdCtx->tunKey, &newNbl);
        break;
    case OVS_VPORT_TYPE_VXLAN:
        status = OvsDecapVxlan(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                               &ovsFwdCtx->tunKey, &newNbl);
        break;
    case OVS_VPORT_TYPE_STT:
        status = OvsDecapStt(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                             &ovsFwdCtx->tunKey, &newNbl);
        if (status == NDIS_STATUS_SUCCESS && newNbl == NULL) {
            /* This was an STT-LSO Fragment */
            dropReason = L"OVS-STT segment is cached";
        }
        break;
    case OVS_VPORT_TYPE_GENEVE:
        status = OvsDecapGeneve(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                                &ovsFwdCtx->tunKey, &newNbl);
        break;
    default:
        OVS_LOG_ERROR("Rx: Unhandled tunnel type: %d\n",
                      tunnelRxVport->ovsType);
        ASSERT(! "Rx: Unhandled tunnel type");
        status = NDIS_STATUS_NOT_SUPPORTED;
    }

    if (status != NDIS_STATUS_SUCCESS) {
        ovsActionStats.failedDecap++;
        goto dropNbl;
    }

    /*
     * tunnelRxNic and other fields will be cleared, re-init the context
     * before usage.
      */
    OvsCompleteNBLForwardingCtx(ovsFwdCtx, dropReason);

    if (newNbl) {
        /* Decapsulated packet is in a new NBL */
        ovsFwdCtx->tunnelRxNic = tunnelRxVport;
        OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
                             newNbl, tunnelRxVport->portNo, 0,
                             NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                             ovsFwdCtx->completionList,
                             &ovsFwdCtx->layers, FALSE);

        /*
         * Set the NBL's SourcePortId and SourceNicIndex to default values to
         * keep NDIS happy when we forward the packet.
         */
        ovsFwdCtx->fwdDetail->SourcePortId = NDIS_SWITCH_DEFAULT_PORT_ID;
        ovsFwdCtx->fwdDetail->SourceNicIndex = 0;

        status = OvsDoFlowLookupOutput(ovsFwdCtx);
    }
    ASSERT(ovsFwdCtx->curNbl == NULL);
    OvsClearTunRxCtx(ovsFwdCtx);

    return status;

dropNbl:
    OvsCompleteNBLForwardingCtx(ovsFwdCtx,
            L"OVS-dropped due to decap failure");
    OvsClearTunRxCtx(ovsFwdCtx);
    return status;
}


/*
 * --------------------------------------------------------------------------
 * OvsOutputForwardingCtx --
 *     This function outputs an NBL to NDIS or to a tunneling pipeline based on
 *     the ports added so far into 'ovsFwdCtx'.
 *
 * Side effects:
 *     This function consumes the NBL - either by forwarding it successfully to
 *     NDIS, or adding it to the completion list in 'ovsFwdCtx', or freeing it.
 *
 *     Also makes sure that the list of destination ports - tunnel or otherwise is
 *     drained.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsOutputForwardingCtx(OvsForwardingContext *ovsFwdCtx)
{
    NDIS_STATUS status = STATUS_SUCCESS;
    POVS_SWITCH_CONTEXT switchContext = ovsFwdCtx->switchContext;
    PCWSTR dropReason;
    POVS_BUFFER_CONTEXT ctx;

    /*
     * Handle the case where the some of the destination ports are tunneled
     * ports - the non-tunneled ports get a unmodified copy of the NBL, and the
     * tunneling pipeline starts when we output the packet to tunneled port.
     */
    if (ovsFwdCtx->destPortsSizeOut > 0) {
        PNET_BUFFER_LIST newNbl = NULL;
        PNET_BUFFER nb;
        UINT32 portsToUpdate =
            ovsFwdCtx->fwdDetail->NumAvailableDestinations -
            (ovsFwdCtx->destPortsSizeIn - ovsFwdCtx->destPortsSizeOut);

        ASSERT(ovsFwdCtx->destinationPorts != NULL);

        /*
         * Create a copy of the packet in order to do encap on it later. Also,
         * don't copy the offload context since the encap'd packet has a
         * different set of headers. This will change when we implement offloads
         * before doing encapsulation.
         */
        if (ovsFwdCtx->tunnelTxNic != NULL || ovsFwdCtx->tunnelRxNic != NULL) {
            POVS_BUFFER_CONTEXT oldCtx, newCtx;
            nb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
            oldCtx = (POVS_BUFFER_CONTEXT)
                NET_BUFFER_LIST_CONTEXT_DATA_START(ovsFwdCtx->curNbl);
            newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext,
                                       ovsFwdCtx->curNbl,
                                       0, 0, TRUE /*copy NBL info*/);
            if (newNbl == NULL) {
                status = NDIS_STATUS_RESOURCES;
                ovsActionStats.noCopiedNbl++;
                dropReason = L"Dropped due to failure to create NBL copy.";
                goto dropit;
            }
            newCtx = (POVS_BUFFER_CONTEXT)
                NET_BUFFER_LIST_CONTEXT_DATA_START(newNbl);
            newCtx->mru = oldCtx->mru;
        }

        /* It does not seem like we'll get here unless 'portsToUpdate' > 0. */
        ASSERT(portsToUpdate > 0);
        status = switchContext->NdisSwitchHandlers.UpdateNetBufferListDestinations(
            switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
            portsToUpdate, ovsFwdCtx->destinationPorts);
        if (status != NDIS_STATUS_SUCCESS) {
            OvsCompleteNBL(ovsFwdCtx->switchContext, newNbl, TRUE);
            ovsActionStats.cannotGrowDest++;
            dropReason = L"Dropped due to failure to update destinations.";
            goto dropit;
        }

        ctx = (POVS_BUFFER_CONTEXT)NET_BUFFER_LIST_CONTEXT_DATA_START(ovsFwdCtx->curNbl);
        if (ctx->mru != 0) {
            OvsDoFragmentNbl(ovsFwdCtx, ctx->mru);
        }

        OvsSendNBLIngress(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                          ovsFwdCtx->sendFlags);
        /* End this pipeline by resetting the corresponding context. */
        ovsFwdCtx->destPortsSizeOut = 0;
        ovsFwdCtx->curNbl = NULL;
        if (newNbl) {
            status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
                                          newNbl, ovsFwdCtx->srcVportNo, 0,
                                          NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                                          ovsFwdCtx->completionList,
                                          &ovsFwdCtx->layers, FALSE);
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"Dropped due to resources.";
                goto dropit;
            }
        }
    }

    if (ovsFwdCtx->tunnelTxNic != NULL) {
        status = OvsTunnelPortTx(ovsFwdCtx);
        ASSERT(ovsFwdCtx->tunnelTxNic == NULL);
        ASSERT(OvsIphIsZero(&(ovsFwdCtx->tunKey.dst)));
    } else if (ovsFwdCtx->tunnelRxNic != NULL) {
        status = OvsTunnelPortRx(ovsFwdCtx);
        ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
        ASSERT(OvsIphIsZero(&(ovsFwdCtx->tunKey.dst)));
    }
    ASSERT(ovsFwdCtx->curNbl == NULL);

    return status;

dropit:
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBLForwardingCtx(ovsFwdCtx, dropReason);
    }

    return status;
}


/*
 * --------------------------------------------------------------------------
 * OvsLookupFlowOutput --
 *     Utility function for external callers to do flow extract, lookup,
 *     actions execute on a given NBL.
 *
 *     Note: If this is being used from a callback function, make sure that the
 *     arguments specified are still valid in the asynchronous context.
 *
 * Side effects:
 *     This function consumes the NBL.
 * --------------------------------------------------------------------------
 */
VOID
OvsLookupFlowOutput(POVS_SWITCH_CONTEXT switchContext,
                    VOID *compList,
                    PNET_BUFFER_LIST curNbl,
                    POVS_VPORT_ENTRY internalVport)
{
    NDIS_STATUS status;
    OvsForwardingContext ovsFwdCtx;

    /* XXX: make sure comp list was not a stack variable previously. */
    OvsCompletionList *completionList = (OvsCompletionList *)compList;

    /*
     * XXX: can internal port disappear while we are busy doing ARP resolution?
     * It could, but will we get this callback from IP helper in that case. Need
     * to check.
     */
    ASSERT(switchContext->countInternalVports > 0);
    status = OvsInitForwardingCtx(&ovsFwdCtx, switchContext, curNbl,
                                  internalVport->portNo, 0,
                                  NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(curNbl),
                                  completionList, NULL, TRUE);
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBLForwardingCtx(&ovsFwdCtx,
                                    L"OVS-Dropped due to resources");
        return;
    }

    ASSERT(FALSE);
    /*
     * XXX: We need to acquire the dispatch lock and the datapath lock.
     */

    OvsDoFlowLookupOutput(&ovsFwdCtx);
}


/*
 * --------------------------------------------------------------------------
 * OvsOutputBeforeSetAction --
 *     Function to be called to complete one set of actions on an NBL, before
 *     we start the next one.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsOutputBeforeSetAction(OvsForwardingContext *ovsFwdCtx)
{
    PNET_BUFFER_LIST newNbl;
    NDIS_STATUS status;

    /*
     * Create a copy and work on the copy after this point. The original NBL is
     * forwarded. One reason to not use the copy for forwarding is that
     * ports have already been added to the original NBL, and it might be
     * inefficient/impossible to remove/re-add them to the copy. There's no
     * notion of removing the ports, the ports need to be marked as
     * "isExcluded". There's seems no real advantage to retaining the original
     * and sending out the copy instead.
     *
     * XXX: We are copying the offload context here. This is to handle actions
     * such as:
     * outport, pop_vlan(), outport, push_vlan(), outport
     *
     * copy size needs to include inner ether + IP + TCP, need to revisit
     * if we support IP options.
     * XXX Head room needs to include the additional encap.
     * XXX copySize check is not considering multiple NBs.
     */
    newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                               0, 0, TRUE /*copy NBL info*/);

    ASSERT(ovsFwdCtx->destPortsSizeOut > 0 ||
           ovsFwdCtx->tunnelTxNic != NULL || ovsFwdCtx->tunnelRxNic != NULL);

    /* Send the original packet out and save the original source port number */
    UINT32 tempVportNo = ovsFwdCtx->srcVportNo;
    status = OvsOutputForwardingCtx(ovsFwdCtx);
    ASSERT(ovsFwdCtx->curNbl == NULL);
    ASSERT(ovsFwdCtx->destPortsSizeOut == 0);
    ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
    ASSERT(ovsFwdCtx->tunnelTxNic == NULL);

    /* If we didn't make a copy, can't continue. */
    if (newNbl == NULL) {
        ovsActionStats.noCopiedNbl++;
        return NDIS_STATUS_RESOURCES;
    }

    /* Finish the remaining actions with the new NBL */
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBL(ovsFwdCtx->switchContext, newNbl, TRUE);
    } else {
        status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
                                      newNbl, tempVportNo, 0,
                                      NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                                      ovsFwdCtx->completionList,
                                      &ovsFwdCtx->layers, FALSE);
    }

    return status;
}


/*
 * --------------------------------------------------------------------------
 * OvsPopFieldInPacketBuf --
 *     Function to pop a specified field of length 'shiftLength' located at
 *     'shiftOffset' from the Ethernet header. The data on the left of the
 *     'shiftOffset' is right shifted.
 *
 *     Returns a pointer to the new start in 'bufferData'.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsPopFieldInPacketBuf(OvsForwardingContext *ovsFwdCtx,
                       UINT32 shiftOffset,
                       UINT32 shiftLength,
                       PUINT8 *bufferData)
{
    PNET_BUFFER curNb;
    PMDL curMdl;
    PUINT8 bufferStart;
    UINT32 packetLen, mdlLen;
    PNET_BUFFER_LIST newNbl;
    NDIS_STATUS status;

    newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                               0, 0, TRUE /* copy NBL info */);
    if (!newNbl) {
        ovsActionStats.noCopiedNbl++;
        return NDIS_STATUS_RESOURCES;
    }

    /* Complete the original NBL and create a copy to modify. */
    OvsCompleteNBLForwardingCtx(ovsFwdCtx, L"OVS-Dropped due to copy");

    status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext, newNbl,
                                  ovsFwdCtx->srcVportNo, 0,
                                  NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                                  NULL, &ovsFwdCtx->layers, FALSE);
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                    L"Dropped due to resouces");
        return NDIS_STATUS_RESOURCES;
    }

    curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
    packetLen = NET_BUFFER_DATA_LENGTH(curNb);
    ASSERT(curNb->Next == NULL);
    curMdl = NET_BUFFER_CURRENT_MDL(curNb);
    NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
    if (!bufferStart) {
        return NDIS_STATUS_RESOURCES;
    }
    mdlLen -= NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
    /* Bail out if L2 + shiftLength is not contiguous in the first buffer. */
    if (MIN(packetLen, mdlLen) < sizeof(EthHdr) + shiftLength) {
        ASSERT(FALSE);
        return NDIS_STATUS_FAILURE;
    }
    bufferStart += NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
    /* XXX At the momemnt !bufferData means it should be treated as VLAN. We
     * should split the function and refactor. */
    if (!bufferData) {
        EthHdr *ethHdr = (EthHdr *)bufferStart;
        if (ethHdr->Type != ETH_TYPE_802_1PQ_NBO) {
            OVS_LOG_ERROR("Invalid ethHdr type %u, nbl %p", ethHdr->Type, ovsFwdCtx->curNbl);
            return NDIS_STATUS_INVALID_PACKET;
        }
    }
    RtlMoveMemory(bufferStart + shiftLength, bufferStart, shiftOffset);
    NdisAdvanceNetBufferDataStart(curNb, shiftLength, FALSE, NULL);

    if (bufferData) {
        *bufferData = bufferStart + shiftLength;
    }

    return NDIS_STATUS_SUCCESS;
}


/*
 * --------------------------------------------------------------------------
 * OvsPopVlanInPktBuf --
 *     Function to pop a VLAN tag when the tag is in the packet buffer.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsPopVlanInPktBuf(OvsForwardingContext *ovsFwdCtx)
{
    NDIS_STATUS status;
    OVS_PACKET_HDR_INFO* layers = &ovsFwdCtx->layers;

    /*
     * Declare a dummy vlanTag structure since we need to compute the size
     * of shiftLength. The NDIS one is a unionized structure.
     */
    NDIS_PACKET_8021Q_INFO vlanTag = {0};
    UINT32 shiftLength = sizeof(vlanTag.TagHeader);
    UINT32 shiftOffset = sizeof(DL_EUI48) + sizeof(DL_EUI48);

    status = OvsPopFieldInPacketBuf(ovsFwdCtx, shiftOffset, shiftLength,
                                    NULL);

    if (status == NDIS_STATUS_SUCCESS) {
        layers->l3Offset -= (UINT16) shiftLength;
        layers->l4Offset -= (UINT16) shiftLength;
    }

    return status;
}


/*
 * --------------------------------------------------------------------------
 * OvsActionMplsPop --
 *     Function to pop the first MPLS label from the current packet.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsActionMplsPop(OvsForwardingContext *ovsFwdCtx,
                 ovs_be16 ethertype)
{
    NDIS_STATUS status;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    EthHdr *ethHdr = NULL;

    status = OvsPopFieldInPacketBuf(ovsFwdCtx, sizeof(*ethHdr),
                                    MPLS_HLEN, (PUINT8*)&ethHdr);
    if (status == NDIS_STATUS_SUCCESS) {
        if (ethHdr && OvsEthertypeIsMpls(ethHdr->Type)) {
            ethHdr->Type = ethertype;
        }

        layers->l3Offset -= MPLS_HLEN;
        layers->l4Offset -= MPLS_HLEN;
    }

    return status;
}


/*
 * --------------------------------------------------------------------------
 * OvsActionMplsPush --
 *     Function to push the MPLS label into the current packet.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsActionMplsPush(OvsForwardingContext *ovsFwdCtx,
                  const struct ovs_action_push_mpls *mpls)
{
    NDIS_STATUS status;
    PNET_BUFFER curNb = NULL;
    PMDL curMdl = NULL;
    PUINT8 bufferStart = NULL;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    EthHdr *ethHdr = NULL;
    MPLSHdr *mplsHdr = NULL;
    UINT32 mdlLen = 0, curMdlOffset = 0;
    PNET_BUFFER_LIST newNbl;

    newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                               layers->l3Offset, MPLS_HLEN, TRUE);
    if (!newNbl) {
        ovsActionStats.noCopiedNbl++;
        return NDIS_STATUS_RESOURCES;
    }
    OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                L"Complete after partial copy.");

    status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
                                  newNbl, ovsFwdCtx->srcVportNo, 0,
                                  NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                                  NULL, &ovsFwdCtx->layers, FALSE);
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                    L"OVS-Dropped due to resources");
        return NDIS_STATUS_RESOURCES;
    }

    curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
    ASSERT(curNb->Next == NULL);

    status = NdisRetreatNetBufferDataStart(curNb, MPLS_HLEN, 0, NULL);
    if (status != NDIS_STATUS_SUCCESS) {
        return status;
    }

    curMdl = NET_BUFFER_CURRENT_MDL(curNb);
    NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
    if (!curMdl) {
        ovsActionStats.noResource++;
        return NDIS_STATUS_RESOURCES;
    }

    curMdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
    mdlLen -= curMdlOffset;
    ASSERT(mdlLen >= MPLS_HLEN);

    ethHdr = (EthHdr *)(bufferStart + curMdlOffset);
    ASSERT(ethHdr);
    RtlMoveMemory(ethHdr, (UINT8*)ethHdr + MPLS_HLEN, sizeof(*ethHdr));
    ethHdr->Type = mpls->mpls_ethertype;

    mplsHdr = (MPLSHdr *)(ethHdr + 1);
    mplsHdr->lse = mpls->mpls_lse;

    layers->l3Offset += MPLS_HLEN;
    layers->l4Offset += MPLS_HLEN;

    return NDIS_STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsUpdateEthHeader --
 *      Updates the ethernet header in ovsFwdCtx.curNbl inline based on the
 *      specified key.
 *----------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsUpdateEthHeader(OvsForwardingContext *ovsFwdCtx,
                   OvsFlowKey *key,
                   const struct ovs_key_ethernet *ethAttr)
{
    PNET_BUFFER curNb;
    PMDL curMdl;
    PUINT8 bufferStart;
    EthHdr *ethHdr;
    UINT32 packetLen, mdlLen;

    curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
    ASSERT(curNb->Next == NULL);
    packetLen = NET_BUFFER_DATA_LENGTH(curNb);
    curMdl = NET_BUFFER_CURRENT_MDL(curNb);
    NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
    if (!bufferStart) {
        ovsActionStats.noResource++;
        return NDIS_STATUS_RESOURCES;
    }
    mdlLen -= NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
    ASSERT(mdlLen > 0);
    /* Bail out if the L2 header is not in a contiguous buffer. */
    if (MIN(packetLen, mdlLen) < sizeof *ethHdr) {
        ASSERT(FALSE);
        return NDIS_STATUS_FAILURE;
    }
    ethHdr = (EthHdr *)(bufferStart + NET_BUFFER_CURRENT_MDL_OFFSET(curNb));

    RtlCopyMemory(ethHdr->Destination, ethAttr->eth_dst, ETH_ADDR_LENGTH);
    RtlCopyMemory(ethHdr->Source, ethAttr->eth_src, ETH_ADDR_LENGTH);
    /* Update l2 flow key */
    RtlCopyMemory(key->l2.dlDst, ethAttr->eth_dst, ETH_ADDR_LENGTH);
    RtlCopyMemory(key->l2.dlSrc, ethAttr->eth_src, ETH_ADDR_LENGTH);

    return NDIS_STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsGetHeaderBySize --
 *      Tries to retrieve a continuous buffer from 'ovsFwdCtx->curnbl' of size
 *      'size'.
 *      If the original buffer is insufficient it will, try to clone the net
 *      buffer list and force the size.
 *      Returns 'NULL' on failure or a pointer to the first byte of the data
 *      in the first net buffer of the net buffer list 'nbl'.
 *----------------------------------------------------------------------------
 */
PUINT8 OvsGetHeaderBySize(OvsForwardingContext *ovsFwdCtx,
                          UINT32 size)
{
    PNET_BUFFER curNb;
    UINT32 mdlLen, packetLen;
    PMDL curMdl;
    ULONG curMdlOffset;
    PUINT8 start;

    curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
    ASSERT(curNb->Next == NULL);
    packetLen = NET_BUFFER_DATA_LENGTH(curNb);
    curMdl = NET_BUFFER_CURRENT_MDL(curNb);
    NdisQueryMdl(curMdl, &start, &mdlLen, LowPagePriority);
    if (!start) {
        ovsActionStats.noResource++;
        return NULL;
    }

    curMdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
    mdlLen -= curMdlOffset;
    ASSERT((INT)mdlLen >= 0);

    /* Count of number of bytes of valid data there are in the first MDL. */
    mdlLen = MIN(packetLen, mdlLen);
    if (mdlLen < size) {
        PNET_BUFFER_LIST newNbl;
        NDIS_STATUS status;
        newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                                   size, 0, TRUE /*copy NBL info*/);
        if (!newNbl) {
            ovsActionStats.noCopiedNbl++;
            return NULL;
        }
        OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                    L"Complete after partial copy.");

        status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
                                      newNbl, ovsFwdCtx->srcVportNo, 0,
                                      NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
                                      NULL, &ovsFwdCtx->layers, FALSE);

        if (status != NDIS_STATUS_SUCCESS) {
            OvsCompleteNBLForwardingCtx(ovsFwdCtx,
                                        L"OVS-Dropped due to resources");
            return NULL;
        }

        curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
        ASSERT(curNb->Next == NULL);
        curMdl = NET_BUFFER_CURRENT_MDL(curNb);
        NdisQueryMdl(curMdl, &start, &mdlLen, LowPagePriority);
        if (!curMdl) {
            ovsActionStats.noResource++;
            return NULL;
        }
        curMdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
        mdlLen -= curMdlOffset;
        ASSERT(mdlLen >= size);
    }

    return start + curMdlOffset;
}

/*
 *----------------------------------------------------------------------------
 * OvsUpdateUdpPorts --
 *      Updates the UDP source or destination port in ovsFwdCtx.curNbl inline
 *      based on the specified key.
 *----------------------------------------------------------------------------
 */
NDIS_STATUS
OvsUpdateUdpPorts(OvsForwardingContext *ovsFwdCtx,
                  OvsFlowKey *key,
                  const struct ovs_key_udp *udpAttr)
{
    PUINT8 bufferStart;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    UDPHdr *udpHdr = NULL;

    ASSERT(layers->value != 0);

    if (!layers->isUdp) {
        ovsActionStats.noCopiedNbl++;
        return NDIS_STATUS_FAILURE;
    }

    bufferStart = OvsGetHeaderBySize(ovsFwdCtx, layers->l7Offset);
    if (!bufferStart) {
        return NDIS_STATUS_RESOURCES;
    }

    udpHdr = (UDPHdr *)(bufferStart + layers->l4Offset);
    if (udpHdr->check) {
        if (udpHdr->source != udpAttr->udp_src) {
            udpHdr->check = ChecksumUpdate16(udpHdr->check, udpHdr->source,
                                             udpAttr->udp_src);
            udpHdr->source = udpAttr->udp_src;
            key->ipKey.l4.tpSrc = udpAttr->udp_src;
        }
        if (udpHdr->dest != udpAttr->udp_dst) {
            udpHdr->check = ChecksumUpdate16(udpHdr->check, udpHdr->dest,
                                             udpAttr->udp_dst);
            udpHdr->dest = udpAttr->udp_dst;
            key->ipKey.l4.tpDst = udpAttr->udp_dst;
        }
    } else {
        udpHdr->source = udpAttr->udp_src;
        key->ipKey.l4.tpSrc = udpAttr->udp_src;
        udpHdr->dest = udpAttr->udp_dst;
        key->ipKey.l4.tpDst = udpAttr->udp_dst;
    }

    return NDIS_STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsUpdateTcpPorts --
 *      Updates the TCP source or destination port in ovsFwdCtx.curNbl inline
 *      based on the specified key.
 *----------------------------------------------------------------------------
 */
NDIS_STATUS
OvsUpdateTcpPorts(OvsForwardingContext *ovsFwdCtx,
                  OvsFlowKey *key,
                  const struct ovs_key_tcp *tcpAttr)
{
    PUINT8 bufferStart;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    TCPHdr *tcpHdr = NULL;

    ASSERT(layers->value != 0);

    if (!layers->isTcp) {
        ovsActionStats.noCopiedNbl++;
        return NDIS_STATUS_FAILURE;
    }

    bufferStart = OvsGetHeaderBySize(ovsFwdCtx, layers->l7Offset);
    if (!bufferStart) {
        return NDIS_STATUS_RESOURCES;
    }

    tcpHdr = (TCPHdr *)(bufferStart + layers->l4Offset);

    if (tcpHdr->source != tcpAttr->tcp_src) {
        tcpHdr->check = ChecksumUpdate16(tcpHdr->check, tcpHdr->source,
                                         tcpAttr->tcp_src);
        tcpHdr->source = tcpAttr->tcp_src;
        key->ipKey.l4.tpSrc = tcpAttr->tcp_src;
    }
    if (tcpHdr->dest != tcpAttr->tcp_dst) {
        tcpHdr->check = ChecksumUpdate16(tcpHdr->check, tcpHdr->dest,
                                         tcpAttr->tcp_dst);
        tcpHdr->dest = tcpAttr->tcp_dst;
        key->ipKey.l4.tpDst = tcpAttr->tcp_dst;
    }

    return NDIS_STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsUpdateAddressAndPort --
 *      Updates the source/destination IP and port fields in
 *      ovsFwdCtx.curNbl inline based on the specified key.
 *----------------------------------------------------------------------------
 */
NDIS_STATUS
OvsUpdateAddressAndPort(OvsForwardingContext *ovsFwdCtx,
                        UINT32 newAddr, UINT16 newPort,
                        BOOLEAN isSource, BOOLEAN isTx)
{
    PUINT8 bufferStart;
    UINT32 hdrSize;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    IPHdr *ipHdr;
    TCPHdr *tcpHdr = NULL;
    UDPHdr *udpHdr = NULL;
    UINT32 *addrField = NULL;
    UINT16 *portField = NULL;
    UINT16 *checkField = NULL;
    BOOLEAN l4Offload = FALSE;
    NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO csumInfo;
    UINT16  preNatPseudoChecksum = 0;
    BOOLEAN preservePseudoChecksum = FALSE;

    ASSERT(layers->value != 0);

    if (layers->isTcp || layers->isUdp) {
        hdrSize = layers->l4Offset +
                  layers->isTcp ? sizeof (*tcpHdr) : sizeof (*udpHdr);
    } else {
        hdrSize = layers->l3Offset + sizeof (*ipHdr);
    }

    bufferStart = OvsGetHeaderBySize(ovsFwdCtx, hdrSize);
    if (!bufferStart) {
        return NDIS_STATUS_RESOURCES;
    }

    ipHdr = (IPHdr *)(bufferStart + layers->l3Offset);

    if (layers->isTcp) {
        tcpHdr = (TCPHdr *)(bufferStart + layers->l4Offset);
    } else if (layers->isUdp) {
        udpHdr = (UDPHdr *)(bufferStart + layers->l4Offset);
    }

    csumInfo.Value = NET_BUFFER_LIST_INFO(ovsFwdCtx->curNbl,
                                          TcpIpChecksumNetBufferListInfo);

    /*
     * Adjust the IP header inline as dictated by the action, and also update
     * the IP and the TCP checksum for the data modified.
     *
     * In the future, this could be optimized to make one call to
     * ChecksumUpdate32(). Ignoring this for now, since for the most common
     * case, we only update the TTL.
     */
     /*Only tx direction the checksum value will be reset to be PseudoChecksum*/
    if (!isTx) {
        preNatPseudoChecksum = IPPseudoChecksum(&ipHdr->saddr, &ipHdr->daddr,
            tcpHdr ? IPPROTO_TCP : IPPROTO_UDP,
            ntohs(ipHdr->tot_len) - ipHdr->ihl * 4);
    }

    if (isSource) {
        addrField = &ipHdr->saddr;
        if (tcpHdr) {
            portField = &tcpHdr->source;
            checkField = &tcpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.TcpChecksum :
                        ((BOOLEAN)csumInfo.Receive.TcpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.TcpChecksumFailed);
        } else if (udpHdr) {
            portField = &udpHdr->source;
            checkField = &udpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.UdpChecksum :
                        ((BOOLEAN)csumInfo.Receive.UdpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.UdpChecksumFailed);
        }
        if (!isTx && l4Offload) {
            if (*checkField == preNatPseudoChecksum) {
                preservePseudoChecksum = TRUE;
            }
        }
        if (isTx && l4Offload || preservePseudoChecksum) {
            *checkField = IPPseudoChecksum(&newAddr, &ipHdr->daddr,
                tcpHdr ? IPPROTO_TCP : IPPROTO_UDP,
                ntohs(ipHdr->tot_len) - ipHdr->ihl * 4);
        }
    } else {
        addrField = &ipHdr->daddr;
        if (tcpHdr) {
            portField = &tcpHdr->dest;
            checkField = &tcpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.TcpChecksum :
                        ((BOOLEAN)csumInfo.Receive.TcpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.TcpChecksumFailed);
        } else if (udpHdr) {
            portField = &udpHdr->dest;
            checkField = &udpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.UdpChecksum :
                        ((BOOLEAN)csumInfo.Receive.UdpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.UdpChecksumFailed);
        }
        if (!isTx && l4Offload) {
            if (*checkField == preNatPseudoChecksum) {
                preservePseudoChecksum = TRUE;
            }
        }

        if (isTx && l4Offload || preservePseudoChecksum) {
            *checkField = IPPseudoChecksum(&ipHdr->saddr, &newAddr,
                tcpHdr ? IPPROTO_TCP : IPPROTO_UDP,
                ntohs(ipHdr->tot_len) - ipHdr->ihl * 4);
        }
    }

    if (*addrField != newAddr) {
        UINT32 oldAddr = *addrField;
        if ((checkField && *checkField != 0) &&
            (!l4Offload || (!isTx && !preservePseudoChecksum))) {
            /* Recompute total checksum. */
            *checkField = ChecksumUpdate32(*checkField, oldAddr,
                                            newAddr);
        }
        if (ipHdr->check != 0) {
            ipHdr->check = ChecksumUpdate32(ipHdr->check, oldAddr,
                                            newAddr);
        }

        *addrField = newAddr;
    }

    if (portField && *portField != newPort) {
        if ((checkField) &&
            (!l4Offload || (!isTx && !preservePseudoChecksum))) {
            /* Recompute total checksum. */
            *checkField = ChecksumUpdate16(*checkField, *portField,
                                           newPort);
        }
        *portField = newPort;
    }
    return NDIS_STATUS_SUCCESS;
}

UINT16
OvsCalculateICMPv6Checksum(struct in6_addr srcAddr,
                        struct in6_addr dstAddr,
                        uint16_t totalLength,
                        uint16_t protocol,
                        uint16_t *icmpStart,
                        uint16_t length)
{
    uint32_t checkSum = 0;
    uint16_t *srcAddressPtr = (uint16_t *)&srcAddr;
    uint16_t *dstAddressPtr = (uint16_t *)&dstAddr;
    uint16_t *value = (uint16_t *)icmpStart;
    int index = 0;

    checkSum = totalLength + protocol;

    for (int i = 0; i < 8; i++) {
        checkSum += ntohs(srcAddressPtr[i]);
        checkSum += ntohs(dstAddressPtr[i]);
    }

    for (index = length; index > 1; index -= 2) {
        checkSum += ntohs(*value);
        value++;
    }

    if (index > 0) {
        checkSum += (uint16_t)(*((uint8_t *)value));
    }

    while ((checkSum >> 16) & 0xffff) {
        checkSum = (checkSum & 0xffff) + ((checkSum >> 16) & 0xffff);
    }

    return htons(~((uint16_t)checkSum));
}

/*
 *-----------------------------------------------------------------------------
 *
 * OvsUpdateAddressAndPortForIpv6--
 *
 *      Update ipv6 address in ovsFwdCtx.curNbl.
 *
 * Results:
 *      None
 *
 * Side effects:
 *      None
 *
 *-----------------------------------------------------------------------------
 */
NDIS_STATUS
OvsUpdateAddressAndPortForIpv6(OvsForwardingContext *ovsFwdCtx,
                               struct in6_addr newAddr, UINT16 newPort,
                               BOOLEAN isSource, BOOLEAN isTx)
{
    PUINT8 bufferStart;
    UINT32 hdrSize;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    IPv6Hdr *ipHdr;
    TCPHdr *tcpHdr = NULL;
    UDPHdr *udpHdr = NULL;
    struct in6_addr *addrField = NULL;
    UINT16 *portField = NULL;
    UINT16 *checkField = NULL;
    BOOLEAN l4Offload = FALSE;
    NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO csumInfo;

    ASSERT(layers->value != 0);

    if (layers->isTcp || layers->isUdp) {
        hdrSize = layers->l4Offset +
                  layers->isTcp ? sizeof (*tcpHdr) : sizeof (*udpHdr);
    } else {
        hdrSize = layers->l3Offset + sizeof (*ipHdr);
    }

    csumInfo.Value = NET_BUFFER_LIST_INFO(ovsFwdCtx->curNbl,
                                          TcpIpChecksumNetBufferListInfo);

    bufferStart = OvsGetHeaderBySize(ovsFwdCtx, hdrSize);
    if (!bufferStart) {
        return NDIS_STATUS_RESOURCES;
    }

    ipHdr = (IPv6Hdr *)(bufferStart + layers->l3Offset);

    if (layers->isTcp) {
        tcpHdr = (TCPHdr *)(bufferStart + layers->l4Offset);
    } else if (layers->isUdp) {
        udpHdr = (UDPHdr *)(bufferStart + layers->l4Offset);
    }

    if (isSource) {
        addrField = &ipHdr->saddr;
        if (tcpHdr) {
            portField = &tcpHdr->source;
            checkField = &tcpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.TcpChecksum :
                        ((BOOLEAN)csumInfo.Receive.TcpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.TcpChecksumFailed);
        } else if (udpHdr) {
            portField = &udpHdr->source;
            checkField = &udpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.UdpChecksum :
                        ((BOOLEAN)csumInfo.Receive.UdpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.UdpChecksumFailed);
        }
        if (isTx && l4Offload) {
            *checkField = IPv6PseudoChecksum((UINT32 *)&newAddr, (UINT32 *)&ipHdr->daddr,
                                             tcpHdr ? IPPROTO_TCP : IPPROTO_UDP,
                                             ntohs(ipHdr->payload_len) -
                                                  (ovsFwdCtx->layers.l4Offset - ovsFwdCtx->layers.l3Offset));
        }
    } else {
        addrField = &ipHdr->daddr;
        if (tcpHdr) {
            portField = &tcpHdr->dest;
            checkField = &tcpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.TcpChecksum :
                        ((BOOLEAN)csumInfo.Receive.TcpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.TcpChecksumFailed);
        } else if (udpHdr) {
            portField = &udpHdr->dest;
            checkField = &udpHdr->check;
            l4Offload = isTx ? (BOOLEAN)csumInfo.Transmit.UdpChecksum :
                        ((BOOLEAN)csumInfo.Receive.UdpChecksumSucceeded ||
                         (BOOLEAN)csumInfo.Receive.UdpChecksumFailed);
        }

        if (isTx && l4Offload) {
            *checkField = IPv6PseudoChecksum((UINT32 *)&ipHdr->saddr, (UINT32 *)&newAddr,
                                             tcpHdr ? IPPROTO_TCP : IPPROTO_UDP,
                                             ntohs(ipHdr->payload_len) -
                                             (ovsFwdCtx->layers.l4Offset - ovsFwdCtx->layers.l3Offset));
        }
    }

    if (memcmp(addrField, &newAddr, sizeof(struct in6_addr))) {
        if ((checkField && *checkField != 0) && (!l4Offload || !isTx)) {
            uint32_t *oldField = (uint32_t *)addrField;
            uint32_t *newField = (uint32_t *)&newAddr;
            *checkField = ChecksumUpdate32(*checkField, oldField[0], newField[0]);
            *checkField = ChecksumUpdate32(*checkField, oldField[1], newField[1]);
            *checkField = ChecksumUpdate32(*checkField, oldField[2], newField[2]);
            *checkField = ChecksumUpdate32(*checkField, oldField[3], newField[3]);
        }

        *addrField = newAddr;

        if (layers->isIcmp) {
            ICMPHdr *icmp =(ICMPHdr *)(bufferStart + layers->l4Offset);
            icmp->checksum = 0x00;
            icmp->checksum = OvsCalculateICMPv6Checksum(ipHdr->saddr, ipHdr->daddr,
                                                        ntohs(ipHdr->payload_len),
                                                        IPPROTO_ICMPV6,
                                                        (uint16_t *)icmp,
                                                        ntohs(ipHdr->payload_len));
        }
    }

    if (portField && *portField != newPort) {
        if ((checkField) && (!l4Offload || !isTx)) {
            /* Recompute total checksum. */
            *checkField = ChecksumUpdate16(*checkField, *portField,
                                           newPort);
        }
        *portField = newPort;
    }

    return NDIS_STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsUpdateIPv4Header --
 *      Updates the IPv4 header in ovsFwdCtx.curNbl inline based on the
 *      specified key.
 *----------------------------------------------------------------------------
 */
NDIS_STATUS
OvsUpdateIPv4Header(OvsForwardingContext *ovsFwdCtx,
                    OvsFlowKey *key,
                    const struct ovs_key_ipv4 *ipAttr)
{
    PUINT8 bufferStart;
    UINT32 hdrSize;
    OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
    IPHdr *ipHdr;
    TCPHdr *tcpHdr = NULL;
    UDPHdr *udpHdr = NULL;

    ASSERT(layers->value != 0);

    if (layers->isTcp || layers->isUdp) {
        hdrSize = layers->l4Offset +
                  layers->isTcp ? sizeof (*tcpHdr) : sizeof (*udpHdr);
    } else {
        hdrSize = layers->l3Offset + sizeof (*ipHdr);
    }

    bufferStart = OvsGetHeaderBySize(ovsFwdCtx, hdrSize);
    if (!bufferStart) {
        return NDIS_STATUS_RESOURCES;
    }

    ipHdr = (IPHdr *)(bufferStart + layers->l3Offset);

    if (layers->isTcp) {
        tcpHdr = (TCPHdr *)(bufferStart + layers->l4Offset);
    } else if (layers->isUdp) {
        udpHdr = (UDPHdr *)(bufferStart + layers->l4Offset);
    }

    /*
     * Adjust the IP header inline as dictated by the action, and also update
     * the IP and the TCP checksum for the data modified.
     *
     * In the future, this could be optimized to make one call to
     * ChecksumUpdate32(). Ignoring this for now, since for the most common
     * case, we only update the TTL.
     */
    if (ipHdr->saddr != ipAttr->ipv4_src) {
        if (tcpHdr) {
            tcpHdr->check = ChecksumUpdate32(tcpHdr->check, ipHdr->saddr,
                                             ipAttr->ipv4_src);
        } else if (udpHdr && udpHdr->check) {
            udpHdr->check = ChecksumUpdate32(udpHdr->check, ipHdr->saddr,
                                             ipAttr->ipv4_src);
        }

        if (ipHdr->check != 0) {
            ipHdr->check = ChecksumUpdate32(ipHdr->check, ipHdr->saddr,
                                            ipAttr->ipv4_src);
        }
        ipHdr->saddr = ipAttr->ipv4_src;
        key->ipKey.nwSrc = ipAttr->ipv4_src;
    }
    if (ipHdr->daddr != ipAttr->ipv4_dst) {
        if (tcpHdr) {
            tcpHdr->check = ChecksumUpdate32(tcpHdr->check, ipHdr->daddr,
                                             ipAttr->ipv4_dst);
        } else if (udpHdr && udpHdr->check) {
            udpHdr->check = ChecksumUpdate32(udpHdr->check, ipHdr->daddr,
                                             ipAttr->ipv4_dst);
        }

        if (ipHdr->check != 0) {
            ipHdr->check = ChecksumUpdate32(ipHdr->check, ipHdr->daddr,
                                            ipAttr->ipv4_dst);
        }
        ipHdr->daddr = ipAttr->ipv4_dst;
        key->ipKey.nwDst = ipAttr->ipv4_dst;
    }
    if (ipHdr->protocol != ipAttr->ipv4_proto) {
        UINT16 oldProto = (ipHdr->protocol << 16) & 0xff00;
        UINT16 newProto = (ipAttr->ipv4_proto << 16) & 0xff00;
        if (tcpHdr) {
            tcpHdr->check = ChecksumUpdate16(tcpHdr->check, oldProto, newProto);
        } else if (udpHdr && udpHdr->check) {
            udpHdr->check = ChecksumUpdate16(udpHdr->check, oldProto, newProto);
        }

        if (ipHdr->check != 0) {
            ipHdr->check = ChecksumUpdate16(ipHdr->check, oldProto, newProto);
        }
        ipHdr->protocol = ipAttr->ipv4_proto;
        key->ipKey.nwProto = ipAttr->ipv4_proto;
    }
    if (ipHdr->ttl != ipAttr->ipv4_ttl) {
        UINT16 oldTtl = (ipHdr->ttl) & 0xff;
        UINT16 newTtl = (ipAttr->ipv4_ttl) & 0xff;
        if (ipHdr->check != 0) {
            ipHdr->check = ChecksumUpdate16(ipHdr->check, oldTtl, newTtl);
        }
        ipHdr->ttl = ipAttr->ipv4_ttl;
        key->ipKey.nwTtl = ipAttr->ipv4_ttl;
    }
    if (ipHdr->dscp != (ipAttr->ipv4_tos & 0xfc)) {
        /* ECN + DSCP */
        UINT8 newTos = (ipHdr->tos & 0x3) | (ipAttr->ipv4_tos & 0xfc);
        if (ipHdr->check != 0) {
            ipHdr->check = ChecksumUpdate16(ipHdr->check, ipHdr->tos, newTos);
        }
        ipHdr->tos = newTos;
        key->ipKey.nwTos = newTos;
    }

    return NDIS_STATUS_SUCCESS;
}

/*
 * --------------------------------------------------------------------------
 * OvsExecuteSetAction --
 *      Executes a set() action, but storing the actions into 'ovsFwdCtx'
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsExecuteSetAction(OvsForwardingContext *ovsFwdCtx,
                    OvsFlowKey *key,
                    UINT64 *hash,
                    const PNL_ATTR a)
{
    enum ovs_key_attr type = NlAttrType(a);
    NDIS_STATUS status = NDIS_STATUS_SUCCESS;

    switch (type) {
    case OVS_KEY_ATTR_ETHERNET:
        status = OvsUpdateEthHeader(ovsFwdCtx, key,
            NlAttrGetUnspec(a, sizeof(struct ovs_key_ethernet)));
        break;

    case OVS_KEY_ATTR_IPV4:
        status = OvsUpdateIPv4Header(ovsFwdCtx, key,
            NlAttrGetUnspec(a, sizeof(struct ovs_key_ipv4)));
        break;

    case OVS_KEY_ATTR_TUNNEL:
    {
        OvsIPTunnelKey tunKey = { 0 };
        tunKey.flow_hash = (uint16)(hash ? *hash : OvsHashFlow(key));
        tunKey.dst_port = key->ipKey.l4.tpDst;
        NTSTATUS convertStatus = OvsTunnelAttrToIPTunnelKey((PNL_ATTR)a, &tunKey);
        status = SUCCEEDED(convertStatus) ? NDIS_STATUS_SUCCESS : NDIS_STATUS_FAILURE;
        ASSERT(status == NDIS_STATUS_SUCCESS);
        RtlCopyMemory(&ovsFwdCtx->tunKey, &tunKey, sizeof ovsFwdCtx->tunKey);
        RtlCopyMemory(&key->tunKey, &tunKey, sizeof key->tunKey);
        break;
    }

    case OVS_KEY_ATTR_UDP:
        status = OvsUpdateUdpPorts(ovsFwdCtx, key,
            NlAttrGetUnspec(a, sizeof(struct ovs_key_udp)));
        break;

    case OVS_KEY_ATTR_TCP:
        status = OvsUpdateTcpPorts(ovsFwdCtx, key,
            NlAttrGetUnspec(a, sizeof(struct ovs_key_tcp)));
        break;

    default:
        OVS_LOG_INFO("Unhandled attribute %#x", type);
        break;
    }
    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsExecuteRecirc --
 *     The function adds a deferred action to allow the current packet, nbl,
 *     to re-enter datapath packet processing.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsExecuteRecirc(OvsForwardingContext *ovsFwdCtx,
                 OvsFlowKey *key,
                 const PNL_ATTR actions,
                 int rem)
{
    POVS_DEFERRED_ACTION deferredAction = NULL;
    PNET_BUFFER_LIST newNbl = NULL;

    if (!NlAttrIsLast(actions, rem)) {
        /*
         * Recirc action is the not the last action of the action list, so we
         * need to clone the packet.
         */
        newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                                   0, 0, TRUE /*copy NBL info*/);
        /*
         * Skip the recirc action when out of memory, but continue on with the
         * rest of the action list.
         */
        if (newNbl == NULL) {
            ovsActionStats.noCopiedNbl++;
            return NDIS_STATUS_SUCCESS;
        }
    }

    if (newNbl) {
        deferredAction = OvsAddDeferredActions(newNbl, key, &(ovsFwdCtx->layers),
                                               NULL);
    } else {
        deferredAction = OvsAddDeferredActions(ovsFwdCtx->curNbl, key,
                                              &(ovsFwdCtx->layers), NULL);
    }

    if (deferredAction) {
        deferredAction->key.recircId = NlAttrGetU32(actions);
    } else {
        if (newNbl) {
            ovsActionStats.deferredActionsQueueFull++;
            OvsCompleteNBL(ovsFwdCtx->switchContext, newNbl, TRUE);
        }
    }

    return NDIS_STATUS_SUCCESS;
}

/*
 * --------------------------------------------------------------------------
 * OvsExecuteHash --
 *     The function updates datapath hash read from userspace.
 * --------------------------------------------------------------------------
 */
VOID
OvsExecuteHash(OvsFlowKey *key,
               const PNL_ATTR attr)
{
    struct ovs_action_hash *hash_act = NlAttrData(attr);
    UINT32 hash = 0;

    hash = (UINT32)OvsHashFlow(key);
    hash = OvsJhashWords(&hash, 1, hash_act->hash_basis);
    if (!hash)
        hash = 1;

    key->dpHash = hash;
}

/*
 * --------------------------------------------------------------------------
 * OvsOutputUserspaceAction --
 *      This function sends the packet to userspace according to nested
 *      %OVS_USERSPACE_ATTR_* attributes.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsOutputUserspaceAction(OvsForwardingContext *ovsFwdCtx,
                         OvsFlowKey *key,
                         const PNL_ATTR attr)
{
    NTSTATUS status = NDIS_STATUS_SUCCESS;
    PNL_ATTR userdataAttr;
    PNL_ATTR egrTunAttr = NULL;
    POVS_PACKET_QUEUE_ELEM elem;
    POVS_PACKET_HDR_INFO layers = &ovsFwdCtx->layers;
    BOOLEAN isRecv = FALSE;
    OVS_FWD_INFO fwdInfo;
    OvsIPTunnelKey tunKey;

    POVS_VPORT_ENTRY vport = OvsFindVportByPortNo(ovsFwdCtx->switchContext,
                                                  ovsFwdCtx->srcVportNo);

    if (vport) {
        if (vport->isExternal ||
            OvsIsTunnelVportType(vport->ovsType)) {
            isRecv = TRUE;
        }
    }

    userdataAttr = NlAttrFindNested(attr, OVS_USERSPACE_ATTR_USERDATA);
    /* Indicate the packet is from egress-tunnel direction */
    egrTunAttr = NlAttrFindNested(attr, OVS_USERSPACE_ATTR_EGRESS_TUN_PORT);

    /* Fill tunnel key to export to usersspace to calculate the template id */
    if (egrTunAttr) {
        RtlZeroMemory(&tunKey,  sizeof tunKey);
        RtlCopyMemory(&tunKey, &ovsFwdCtx->tunKey, sizeof tunKey);
        if (!OvsIphIsZero(&(tunKey.src))) {
            status = OvsLookupIPhFwdInfo(tunKey.src, tunKey.dst, &fwdInfo);
            if (status == NDIS_STATUS_SUCCESS &&
                OvsIphAddrEquals(&(tunKey.dst), &(fwdInfo.dstIphAddr))) {
                OvsCopyIphAddress(&(tunKey.src), &fwdInfo.srcIphAddr);
            }
        }
        tunKey.flow_hash = tunKey.flow_hash ? tunKey.flow_hash : MAXINT16;
    }

    elem = OvsCreateQueueNlPacket(NlAttrData(userdataAttr),
                                  NlAttrGetSize(userdataAttr),
                                  OVS_PACKET_CMD_ACTION,
                                  vport, key,
                                  egrTunAttr ? &(tunKey) : NULL,
                                  ovsFwdCtx->curNbl,
                                  NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl),
                                  isRecv,
                                  layers);
    if (elem) {
        LIST_ENTRY missedPackets;
        InitializeListHead(&missedPackets);
        InsertTailList(&missedPackets, &elem->link);
        OvsQueuePackets(&missedPackets, 1);
    } else {
        status = NDIS_STATUS_FAILURE;
    }

    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsExecuteSampleAction --
 *      Executes actions based on probability, as specified in the nested
 *      %OVS_SAMPLE_ATTR_* attributes.
 * --------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsExecuteSampleAction(OvsForwardingContext *ovsFwdCtx,
                       OvsFlowKey *key,
                       const PNL_ATTR attr)
{
    PNET_BUFFER_LIST newNbl = NULL;
    PNL_ATTR actionsList = NULL;
    PNL_ATTR a = NULL;
    INT rem = 0;

    SRand();
    NL_ATTR_FOR_EACH_UNSAFE(a, rem, NlAttrData(attr), NlAttrGetSize(attr)) {
        switch (NlAttrType(a)) {
        case OVS_SAMPLE_ATTR_PROBABILITY:
        {
            UINT32 probability = NlAttrGetU32(a);

            if (!probability || Rand() > probability) {
                return 0;
            }
            break;
        }
        case OVS_SAMPLE_ATTR_ACTIONS:
            actionsList = a;
            break;
        }
    }

    if (actionsList) {
        rem = NlAttrGetSize(actionsList);
        a = (PNL_ATTR)NlAttrData(actionsList);
    }

    if (!rem) {
        /* Actions list is empty, do nothing */
        return STATUS_SUCCESS;
    }

    /*
     * The only known usage of sample action is having a single user-space
     * action. Treat this usage as a special case.
     */
    if (NlAttrType(a) == OVS_ACTION_ATTR_USERSPACE &&
        NlAttrIsLast(a, rem)) {
        return OvsOutputUserspaceAction(ovsFwdCtx, key, a);
    }

    newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
                               0, 0, TRUE /*copy NBL info*/);
    if (newNbl == NULL) {
        /*
         * Skip the sample action when out of memory, but continue on with the
         * rest of the action list.
         */
        ovsActionStats.noCopiedNbl++;
        return STATUS_SUCCESS;
    }

    if (!OvsAddDeferredActions(newNbl, key, &(ovsFwdCtx->layers), a)) {
        OVS_LOG_INFO(
            "Deferred actions limit reached, dropping sample action.");
        OvsCompleteNBL(ovsFwdCtx->switchContext, newNbl, TRUE);
    }

    return STATUS_SUCCESS;
}

/*
 * --------------------------------------------------------------------------
 * OvsDoExecuteActions --
 *     Interpret and execute the specified 'actions' on the specified packet
 *     'curNbl'. The expectation is that if the packet needs to be dropped
 *     (completed) for some reason, it is added to 'completionList' so that the
 *     caller can complete the packet. If 'completionList' is NULL, the NBL is
 *     assumed to be generated by OVS and freed up. Otherwise, the function
 *     consumes the NBL by generating a NDIS send indication for the packet.
 *
 *     There are one or more of "clone" NBLs that may get generated while
 *     executing the actions. Upon any failures, the "cloned" NBLs are freed up,
 *     and the caller does not have to worry about them.
 *
 *     Success or failure is returned based on whether the specified actions
 *     were executed successfully on the packet or not.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsDoExecuteActions(POVS_SWITCH_CONTEXT switchContext,
                    OvsCompletionList *completionList,
                    PNET_BUFFER_LIST curNbl,
                    UINT32 portNo,
                    ULONG sendFlags,
                    OvsFlowKey *key,
                    UINT64 *hash,
                    OVS_PACKET_HDR_INFO *layers,
                    const PNL_ATTR actions,
                    INT actionsLen)
{
    PNL_ATTR a;
    INT rem;
    UINT32 dstPortID;
    OvsForwardingContext ovsFwdCtx;
    PCWSTR dropReason = L"";
    NDIS_STATUS status;
    PNDIS_SWITCH_FORWARDING_DETAIL_NET_BUFFER_LIST_INFO fwdDetail =
        NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(curNbl);

    /* XXX: ASSERT that the flow table lock is held. */
    status = OvsInitForwardingCtx(&ovsFwdCtx, switchContext, curNbl, portNo,
                                  sendFlags, fwdDetail, completionList,
                                  layers, TRUE);
    if (status != NDIS_STATUS_SUCCESS) {
        dropReason = L"OVS-initing destination port list failed";
        goto dropit;
    }

    if (actionsLen == 0) {
        dropReason = L"OVS-Dropped due to Flow action";
        ovsActionStats.zeroActionLen++;
        goto dropit;
    }

    NL_ATTR_FOR_EACH_UNSAFE (a, rem, actions, actionsLen) {
        switch(NlAttrType(a)) {
        case OVS_ACTION_ATTR_OUTPUT:
            dstPortID = NlAttrGetU32(a);
            status = OvsAddPorts(&ovsFwdCtx, key, dstPortID,
                                              TRUE, TRUE);
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-adding destination port failed";
                goto dropit;
            }
            break;

        case OVS_ACTION_ATTR_PUSH_VLAN:
        {
            struct ovs_action_push_vlan *vlan;
            PVOID vlanTagValue;
            PNDIS_NET_BUFFER_LIST_8021Q_INFO vlanTag;

            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            vlanTagValue = NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
                                                Ieee8021QNetBufferListInfo);
            if (vlanTagValue != NULL) {
                /*
                 * XXX: We don't support double VLAN tag offload. In such cases,
                 * we need to insert the existing one into the packet buffer,
                 * and add the new one as offload. This will take care of
                 * guest tag-in-tag case as well as OVS rules that specify
                 * tag-in-tag.
                 */
            } else {
                 vlanTagValue = 0;
                 vlanTag = (PNDIS_NET_BUFFER_LIST_8021Q_INFO)(PVOID *)&vlanTagValue;
                 vlan = (struct ovs_action_push_vlan *)NlAttrGet((const PNL_ATTR)a);
                 vlanTag->TagHeader.VlanId = ntohs(vlan->vlan_tci) & 0xfff;
                 vlanTag->TagHeader.UserPriority = ntohs(vlan->vlan_tci) >> 13;
                 vlanTag->TagHeader.CanonicalFormatId = (ntohs(vlan->vlan_tci) >> 12) & 0x1;

                 NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
                                      Ieee8021QNetBufferListInfo) = vlanTagValue;
            }
            break;
        }

        case OVS_ACTION_ATTR_POP_VLAN:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            if (NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
                                     Ieee8021QNetBufferListInfo) != 0) {
                NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
                                     Ieee8021QNetBufferListInfo) = 0;
            } else {
                /*
                 * The VLAN tag is inserted into the packet buffer. Pop the tag
                 * by packet buffer modification.
                 */
                status = OvsPopVlanInPktBuf(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    OVS_LOG_ERROR("OVS-pop vlan action failed status = %lu", status);
                    dropReason = L"OVS-pop vlan action failed";
                    goto dropit;
                }
            }
            /* Reset vlan header info in flowkey. */
            key->l2.vlanKey.vlanTci = 0;
            key->l2.vlanKey.vlanTpid = 0;
            break;
        }

        case OVS_ACTION_ATTR_PUSH_MPLS:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            status = OvsActionMplsPush(&ovsFwdCtx,
                                       (struct ovs_action_push_mpls *)NlAttrGet
                                       ((const PNL_ATTR)a));
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-push MPLS action failed";
                goto dropit;
            }
            layers->l3Offset += MPLS_HLEN;
            layers->l4Offset += MPLS_HLEN;
            break;
        }

        case OVS_ACTION_ATTR_POP_MPLS:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            status = OvsActionMplsPop(&ovsFwdCtx, NlAttrGetBe16(a));
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-pop MPLS action failed";
                goto dropit;
            }
            layers->l3Offset -= MPLS_HLEN;
            layers->l4Offset -= MPLS_HLEN;
            break;
        }

        case OVS_ACTION_ATTR_HASH:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            OvsExecuteHash(key, (const PNL_ATTR)a);
            break;
        }

        case OVS_ACTION_ATTR_CT:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0
                || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            PNET_BUFFER_LIST oldNbl = ovsFwdCtx.curNbl;
            status = OvsExecuteConntrackAction(&ovsFwdCtx, key,
                                               (const PNL_ATTR)a);
            if (status != NDIS_STATUS_SUCCESS) {
                /* Pending NBLs are consumed by Defragmentation. */
                if (status != NDIS_STATUS_PENDING) {
                    OVS_LOG_ERROR("CT Action failed status = %lu", status);
                    dropReason = L"OVS-conntrack action failed";
                } else {
                    /* We added a new pending NBL to be consumed later.
                     * Report to the userspace that the action applied
                     * successfully */
                    status = NDIS_STATUS_SUCCESS;
                }
                goto dropit;
            } else if (oldNbl != ovsFwdCtx.curNbl) {
                /*
                 * OvsIpv4Reassemble/OvsIpv6Reassemble consumes the
                 * original NBL and creates a new one and assigns
                 * it to the curNbl of ovsFwdCtx.
                 */
                OvsInitForwardingCtx(&ovsFwdCtx,
                                     ovsFwdCtx.switchContext,
                                     ovsFwdCtx.curNbl,
                                     ovsFwdCtx.srcVportNo,
                                     ovsFwdCtx.sendFlags,
                                     NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(ovsFwdCtx.curNbl),
                                     ovsFwdCtx.completionList,
                                     &ovsFwdCtx.layers, FALSE);
                key->ipKey.nwFrag = OVS_FRAG_TYPE_NONE;
                key->ipv6Key.nwFrag = OVS_FRAG_TYPE_NONE;
            }
            break;
        }

        case OVS_ACTION_ATTR_RECIRC:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            status = OvsExecuteRecirc(&ovsFwdCtx, key, (const PNL_ATTR)a, rem);
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-recirculation action failed";
                goto dropit;
            }

            if (NlAttrIsLast(a, rem)) {
                goto exit;
            }
            break;
        }

        case OVS_ACTION_ATTR_USERSPACE:
        {
            status = OvsOutputUserspaceAction(&ovsFwdCtx, key,
                                              (const PNL_ATTR)a);
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-Dropped due to failure to queue to "
                             L"userspace";
                goto dropit;
            }
            dropReason = L"OVS-Completed since packet was copied to "
                         L"userspace";
            break;
        }
        case OVS_ACTION_ATTR_SET:
        {
            OvsIPTunnelKey pre_tunKey = { 0 };
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }
            RtlCopyMemory(&pre_tunKey, &key->tunKey, sizeof key->tunKey);
            status = OvsExecuteSetAction(&ovsFwdCtx, key, hash,
                                         (const PNL_ATTR)NlAttrGet
                                         ((const PNL_ATTR)a));
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-set action failed";
                goto dropit;
            }

            if (!OvsIphIsZero(&(key->tunKey.dst)) &&
                 key->l2.offset != OvsGetFlowIPL2Offset(&key->tunKey)) {
                 key->l2.offset = OvsGetFlowIPL2Offset(&ovsFwdCtx.tunKey);
            }
            if (!OvsIphIsZero(&(pre_tunKey.dst))) {
                 /*if pre_tunkey dst is not null in multiple IPV6 Geneve tunnels case,
                  * for broadcast and multicast packet the flow pipeline will set different
                  * tunnel setting on one flow. In such case, it needs to do layers update.
                  * Elsewise it will meet BSOD issue but in IPV4 tunnel the BSOD will not
                  * have construct case to make it happen.
                  */
                 status = OvsExtractLayers(ovsFwdCtx.curNbl, &ovsFwdCtx.layers);
                 if (status != NDIS_STATUS_SUCCESS) {
                     dropReason = L"OVS-set action ExtractLayers failed";
                     goto dropit;
                 }
            }
            break;
        }
        case OVS_ACTION_ATTR_METER: {
            if (OvsMeterExecute(&ovsFwdCtx, NlAttrGetU32(a))) {
                OVS_LOG_INFO("Drop packet");
                dropReason = L"Ovs-meter exceed max rate";
                goto dropit;
            }

            break;
        }
        case OVS_ACTION_ATTR_SAMPLE:
        {
            if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
                || ovsFwdCtx.tunnelRxNic != NULL) {
                status = OvsOutputBeforeSetAction(&ovsFwdCtx);
                if (status != NDIS_STATUS_SUCCESS) {
                    dropReason = L"OVS-adding destination failed";
                    goto dropit;
                }
            }

            status = OvsExecuteSampleAction(&ovsFwdCtx, key,
                                            (const PNL_ATTR)a);
            if (status != NDIS_STATUS_SUCCESS) {
                dropReason = L"OVS-sample action failed";
                goto dropit;
            }
            break;
        }
        default:
            status = NDIS_STATUS_NOT_SUPPORTED;
            break;
        }
    }

    if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
        || ovsFwdCtx.tunnelRxNic != NULL) {
        status = OvsOutputForwardingCtx(&ovsFwdCtx);
        ASSERT(ovsFwdCtx.curNbl == NULL);
    }

    ASSERT(ovsFwdCtx.destPortsSizeOut == 0);
    ASSERT(ovsFwdCtx.tunnelRxNic == NULL);
    ASSERT(ovsFwdCtx.tunnelTxNic == NULL);

dropit:
    /*
     * If curNbl != NULL, it implies the NBL has not been not freed up so far.
     */
    if (ovsFwdCtx.curNbl) {
        OvsCompleteNBLForwardingCtx(&ovsFwdCtx, dropReason);
    }

exit:
    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsActionsExecute --
 *     The function interprets and executes the specified 'actions' on the
 *     specified packet 'curNbl'. See 'OvsDoExecuteActions' description for
 *     more details.
 *
 *     Also executes deferred actions added by recirculation or sample
 *     actions.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsActionsExecute(POVS_SWITCH_CONTEXT switchContext,
                  OvsCompletionList *completionList,
                  PNET_BUFFER_LIST curNbl,
                  UINT32 portNo,
                  ULONG sendFlags,
                  OvsFlowKey *key,
                  UINT64 *hash,
                  OVS_PACKET_HDR_INFO *layers,
                  const PNL_ATTR actions,
                  INT actionsLen)
{
    NDIS_STATUS status;

    status = OvsDoExecuteActions(switchContext, completionList, curNbl,
                                 portNo, sendFlags, key, hash, layers,
                                 actions, actionsLen);

    if (status == STATUS_SUCCESS) {
        status = OvsProcessDeferredActions(switchContext, completionList,
                                           portNo, sendFlags);
    }

    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsDoRecirc --
 *     The function processes the packet 'curNbl' that re-entered datapath
 *     packet processing after a recirculation action.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsDoRecirc(POVS_SWITCH_CONTEXT switchContext,
            OvsCompletionList *completionList,
            PNET_BUFFER_LIST curNbl,
            OvsFlowKey *key,
            UINT32 srcPortNo,
            OVS_PACKET_HDR_INFO *layers)
{
    NDIS_STATUS status;
    OvsFlow *flow;
    OvsForwardingContext ovsFwdCtx = { 0 };
    UINT64 hash = 0;
    ASSERT(layers);

    OvsInitForwardingCtx(&ovsFwdCtx, switchContext, curNbl,
                         srcPortNo, 0,
                         NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(curNbl),
                         completionList, layers, TRUE);
    ASSERT(ovsFwdCtx.switchContext);

    flow = OvsLookupFlow(&ovsFwdCtx.switchContext->datapath, key, &hash, FALSE);
    if (flow) {
        UINT32 level = OvsDeferredActionsLevelGet();

        if (level > DEFERRED_ACTION_EXEC_LEVEL) {
            OvsCompleteNBLForwardingCtx(&ovsFwdCtx,
                L"OVS-Dropped due to deferred actions execution level limit \
                  reached");
            ovsActionStats.deferredActionsExecLimit++;
            ovsFwdCtx.curNbl = NULL;
            return NDIS_STATUS_FAILURE;
        }

        OvsFlowUsed(flow, ovsFwdCtx.curNbl, &ovsFwdCtx.layers);
        ovsFwdCtx.switchContext->datapath.hits++;

        OvsDeferredActionsLevelInc();

        status = OvsDoExecuteActions(ovsFwdCtx.switchContext,
                                     ovsFwdCtx.completionList,
                                     ovsFwdCtx.curNbl,
                                     ovsFwdCtx.srcVportNo,
                                     ovsFwdCtx.sendFlags,
                                     key, &hash, &ovsFwdCtx.layers,
                                     flow->actions, flow->actionsLen);
        ovsFwdCtx.curNbl = NULL;

        OvsDeferredActionsLevelDec();
    } else {
        POVS_VPORT_ENTRY vport = NULL;
        LIST_ENTRY missedPackets;
        UINT32 num = 0;

        ovsFwdCtx.switchContext->datapath.misses++;
        InitializeListHead(&missedPackets);
        vport = OvsFindVportByPortNo(switchContext, srcPortNo);
        if (vport == NULL || vport->ovsState != OVS_STATE_CONNECTED) {
            OvsCompleteNBLForwardingCtx(&ovsFwdCtx,
                L"OVS-Dropped due to port removal");
            ovsActionStats.noVport++;
            return NDIS_STATUS_SUCCESS;
        }
        status = OvsCreateAndAddPackets(NULL, 0, OVS_PACKET_CMD_MISS,
                                        vport, key, ovsFwdCtx.curNbl,
                                        OvsIsExternalVportByPortId(switchContext,
                                            vport->portId),
                                        &ovsFwdCtx.layers,
                                        ovsFwdCtx.switchContext,
                                        &missedPackets, &num);
        if (num) {
            OvsQueuePackets(&missedPackets, num);
        }
        if (status == NDIS_STATUS_SUCCESS) {
            /* Complete the packet since it was copied to user buffer. */
            OvsCompleteNBLForwardingCtx(&ovsFwdCtx,
                L"OVS-Dropped since packet was copied to userspace");
            ovsActionStats.flowMiss++;
        } else {
            OvsCompleteNBLForwardingCtx(&ovsFwdCtx,
                L"OVS-Dropped due to failure to queue to userspace");
            ovsActionStats.failedFlowMiss++;
            status = NDIS_STATUS_FAILURE;
        }
    }

    return status;
}