d75949ca4191a87cbb24429ad8330bfd3a381a85
[cascardo/ovs.git] / datapath-windows / ovsext / Actions.c
1 /*
2  * Copyright (c) 2014 VMware, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "precomp.h"
18
19 #include "Switch.h"
20 #include "Vport.h"
21 #include "Event.h"
22 #include "User.h"
23 #include "NetProto.h"
24 #include "Flow.h"
25 #include "Vxlan.h"
26 #include "Stt.h"
27 #include "Checksum.h"
28 #include "PacketIO.h"
29
30 #ifdef OVS_DBG_MOD
31 #undef OVS_DBG_MOD
32 #endif
33 #define OVS_DBG_MOD OVS_DBG_ACTION
34 #include "Debug.h"
35
36 typedef struct _OVS_ACTION_STATS {
37     UINT64 rxVxlan;
38     UINT64 txVxlan;
39     UINT64 rxStt;
40     UINT64 txStt;
41     UINT64 flowMiss;
42     UINT64 flowUserspace;
43     UINT64 txTcp;
44     UINT32 failedFlowMiss;
45     UINT32 noVport;
46     UINT32 failedFlowExtract;
47     UINT32 noResource;
48     UINT32 noCopiedNbl;
49     UINT32 failedEncap;
50     UINT32 failedDecap;
51     UINT32 cannotGrowDest;
52     UINT32 zeroActionLen;
53     UINT32 failedChecksum;
54 } OVS_ACTION_STATS, *POVS_ACTION_STATS;
55
56 OVS_ACTION_STATS ovsActionStats;
57
58 /*
59  * There a lot of data that needs to be maintained while executing the pipeline
60  * as dictated by the actions of a flow, across different functions at different
61  * levels. Such data is put together in a 'context' structure. Care should be
62  * exercised while adding new members to the structure - only add ones that get
63  * used across multiple stages in the pipeline/get used in multiple functions.
64  */
65 #define OVS_DEST_PORTS_ARRAY_MIN_SIZE 2
66 typedef struct OvsForwardingContext {
67     POVS_SWITCH_CONTEXT switchContext;
68     /* The NBL currently used in the pipeline. */
69     PNET_BUFFER_LIST curNbl;
70     /* NDIS forwarding detail for 'curNbl'. */
71     PNDIS_SWITCH_FORWARDING_DETAIL_NET_BUFFER_LIST_INFO fwdDetail;
72     /* Array of destination ports for 'curNbl'. */
73     PNDIS_SWITCH_FORWARDING_DESTINATION_ARRAY destinationPorts;
74     /* send flags while sending 'curNbl' into NDIS. */
75     ULONG sendFlags;
76     /* Total number of output ports, used + unused, in 'curNbl'. */
77     UINT32 destPortsSizeIn;
78     /* Total number of used output ports in 'curNbl'. */
79     UINT32 destPortsSizeOut;
80     /*
81      * If 'curNbl' is not owned by OVS, they need to be tracked, if they need to
82      * be freed/completed.
83      */
84     OvsCompletionList *completionList;
85     /*
86      * vport number of 'curNbl' when it is passed from the PIF bridge to the INT
87      * bridge. ie. during tunneling on the Rx side.
88      */
89     UINT32 srcVportNo;
90
91     /*
92      * Tunnel key:
93      * - specified in actions during tunneling Tx
94      * - extracted from an NBL during tunneling Rx
95      */
96     OvsIPv4TunnelKey tunKey;
97
98      /*
99      * Tunneling - Tx:
100      * To store the output port, when it is a tunneled port. We don't foresee
101      * multiple tunneled ports as outport for any given NBL.
102      */
103     POVS_VPORT_ENTRY tunnelTxNic;
104
105     /*
106      * Tunneling - Rx:
107      * Points to the Internal port on the PIF Bridge, if the packet needs to be
108      * de-tunneled.
109      */
110     POVS_VPORT_ENTRY tunnelRxNic;
111
112     /* header information */
113     OVS_PACKET_HDR_INFO layers;
114 } OvsForwardingContext;
115
116
117 /*
118  * --------------------------------------------------------------------------
119  * OvsInitForwardingCtx --
120  *     Function to init/re-init the 'ovsFwdCtx' context as the actions pipeline
121  *     is being executed.
122  *
123  * Result:
124  *     NDIS_STATUS_SUCCESS on success
125  *     Other NDIS_STATUS upon failure. Upon failure, it is safe to call
126  *     OvsCompleteNBLForwardingCtx(), since 'ovsFwdCtx' has been initialized
127  *     enough for OvsCompleteNBLForwardingCtx() to do its work.
128  * --------------------------------------------------------------------------
129  */
130 static __inline NDIS_STATUS
131 OvsInitForwardingCtx(OvsForwardingContext *ovsFwdCtx,
132                      POVS_SWITCH_CONTEXT switchContext,
133                      PNET_BUFFER_LIST curNbl,
134                      UINT32 srcVportNo,
135                      ULONG sendFlags,
136                      PNDIS_SWITCH_FORWARDING_DETAIL_NET_BUFFER_LIST_INFO fwdDetail,
137                      OvsCompletionList *completionList,
138                      OVS_PACKET_HDR_INFO *layers,
139                      BOOLEAN resetTunnelInfo)
140 {
141     ASSERT(ovsFwdCtx);
142     ASSERT(switchContext);
143     ASSERT(curNbl);
144     ASSERT(fwdDetail);
145
146     /*
147      * Set values for curNbl and switchContext so upon failures, we have enough
148      * information to do cleanup.
149      */
150     ovsFwdCtx->curNbl = curNbl;
151     ovsFwdCtx->switchContext = switchContext;
152     ovsFwdCtx->completionList = completionList;
153     ovsFwdCtx->fwdDetail = fwdDetail;
154
155     if (fwdDetail->NumAvailableDestinations > 0) {
156         /*
157          * XXX: even though MSDN says GetNetBufferListDestinations() returns
158          * NDIS_STATUS, the header files say otherwise.
159          */
160         switchContext->NdisSwitchHandlers.GetNetBufferListDestinations(
161             switchContext->NdisSwitchContext, curNbl,
162             &ovsFwdCtx->destinationPorts);
163
164         ASSERT(ovsFwdCtx->destinationPorts);
165         /* Ensure that none of the elements are consumed yet. */
166         ASSERT(ovsFwdCtx->destinationPorts->NumElements ==
167                fwdDetail->NumAvailableDestinations);
168     } else {
169         ovsFwdCtx->destinationPorts = NULL;
170     }
171     ovsFwdCtx->destPortsSizeIn = fwdDetail->NumAvailableDestinations;
172     ovsFwdCtx->destPortsSizeOut = 0;
173     ovsFwdCtx->srcVportNo = srcVportNo;
174     ovsFwdCtx->sendFlags = sendFlags;
175     if (layers) {
176         ovsFwdCtx->layers = *layers;
177     } else {
178         RtlZeroMemory(&ovsFwdCtx->layers, sizeof ovsFwdCtx->layers);
179     }
180     if (resetTunnelInfo) {
181         ovsFwdCtx->tunnelTxNic = NULL;
182         ovsFwdCtx->tunnelRxNic = NULL;
183         RtlZeroMemory(&ovsFwdCtx->tunKey, sizeof ovsFwdCtx->tunKey);
184     }
185
186     return NDIS_STATUS_SUCCESS;
187 }
188
189 /*
190  * --------------------------------------------------------------------------
191  * OvsDetectTunnelRxPkt --
192  *     Utility function for an RX packet to detect its tunnel type.
193  *
194  * Result:
195  *  True  - if the tunnel type was detected.
196  *  False - if not a tunnel packet or tunnel type not supported.
197  * --------------------------------------------------------------------------
198  */
199 static __inline BOOLEAN
200 OvsDetectTunnelRxPkt(OvsForwardingContext *ovsFwdCtx,
201                      const OvsFlowKey *flowKey)
202 {
203     POVS_VPORT_ENTRY tunnelVport = NULL;
204
205     /* XXX: we should also check for the length of the UDP payload to pick
206      * packets only if they are at least VXLAN header size.
207      */
208     if (!flowKey->ipKey.nwFrag &&
209         flowKey->ipKey.nwProto == IPPROTO_UDP) {
210         UINT16 dstPort = htons(flowKey->ipKey.l4.tpDst);
211         tunnelVport = OvsFindTunnelVportByDstPort(ovsFwdCtx->switchContext,
212                                                   dstPort,
213                                                   OVS_VPORT_TYPE_VXLAN);
214         if (tunnelVport) {
215             ovsActionStats.rxVxlan++;
216         }
217     } else if (!flowKey->ipKey.nwFrag &&
218                 flowKey->ipKey.nwProto == IPPROTO_TCP) {
219         UINT16 dstPort = htons(flowKey->ipKey.l4.tpDst);
220         tunnelVport = OvsFindTunnelVportByDstPort(ovsFwdCtx->switchContext,
221                                                   dstPort,
222                                                   OVS_VPORT_TYPE_STT);
223         if (tunnelVport) {
224             ovsActionStats.rxStt++;
225         }
226     }
227
228
229     // We might get tunnel packets even before the tunnel gets initialized.
230     if (tunnelVport) {
231         ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
232         ovsFwdCtx->tunnelRxNic = tunnelVport;
233         return TRUE;
234     }
235
236     return FALSE;
237 }
238
239 /*
240  * --------------------------------------------------------------------------
241  * OvsDetectTunnelPkt --
242  *     Utility function to detect if a packet is to be subjected to
243  *     tunneling (Tx) or de-tunneling (Rx). Various factors such as source
244  *     port, destination port, packet contents, and previously setup tunnel
245  *     context are used.
246  *
247  * Result:
248  *  True  - If the packet is to be subjected to tunneling.
249  *          In case of invalid tunnel context, the tunneling functionality is
250  *          a no-op and is completed within this function itself by consuming
251  *          all of the tunneling context.
252  *  False - If not a tunnel packet or tunnel type not supported. Caller should
253  *          process the packet as a non-tunnel packet.
254  * --------------------------------------------------------------------------
255  */
256 static __inline BOOLEAN
257 OvsDetectTunnelPkt(OvsForwardingContext *ovsFwdCtx,
258                    const POVS_VPORT_ENTRY dstVport,
259                    const OvsFlowKey *flowKey)
260 {
261     if (OvsIsInternalVportType(dstVport->ovsType)) {
262         /*
263          * Rx:
264          * The source of NBL during tunneling Rx could be the external
265          * port or if it is being executed from userspace, the source port is
266          * default port.
267          */
268         BOOLEAN validSrcPort =
269             (ovsFwdCtx->fwdDetail->SourcePortId ==
270                  ovsFwdCtx->switchContext->virtualExternalPortId) ||
271             (ovsFwdCtx->fwdDetail->SourcePortId ==
272                  NDIS_SWITCH_DEFAULT_PORT_ID);
273
274         if (validSrcPort && OvsDetectTunnelRxPkt(ovsFwdCtx, flowKey)) {
275             ASSERT(ovsFwdCtx->tunnelTxNic == NULL);
276             ASSERT(ovsFwdCtx->tunnelRxNic != NULL);
277             return TRUE;
278         }
279     } else if (OvsIsTunnelVportType(dstVport->ovsType)) {
280         ASSERT(ovsFwdCtx->tunnelTxNic == NULL);
281         ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
282
283         /*
284          * Tx:
285          * The destination port is a tunnel port. Encapsulation must be
286          * performed only on packets that originate from:
287          * - a VIF port
288          * - a bridge-internal port (packets generated from userspace)
289          * - no port.
290          *
291          * If the packet will not be encapsulated, consume the tunnel context
292          * by clearing it.
293          */
294         if (ovsFwdCtx->srcVportNo != OVS_DEFAULT_PORT_NO) {
295
296             POVS_VPORT_ENTRY vport = OvsFindVportByPortNo(
297                 ovsFwdCtx->switchContext, ovsFwdCtx->srcVportNo);
298
299             if (!vport ||
300                 (vport->ovsType != OVS_VPORT_TYPE_NETDEV &&
301                  !OvsIsBridgeInternalVport(vport))) {
302                 ovsFwdCtx->tunKey.dst = 0;
303             }
304         }
305
306         /* Tunnel the packet only if tunnel context is set. */
307         if (ovsFwdCtx->tunKey.dst != 0) {
308             switch(dstVport->ovsType) {
309             case OVS_VPORT_TYPE_VXLAN:
310                 ovsActionStats.txVxlan++;
311                 break;
312             case OVS_VPORT_TYPE_STT:
313                 ovsActionStats.txStt++;
314                 break;
315             }
316             ovsActionStats.txVxlan++;
317             ovsFwdCtx->tunnelTxNic = dstVport;
318         }
319
320         return TRUE;
321     }
322
323     return FALSE;
324 }
325
326
327 /*
328  * --------------------------------------------------------------------------
329  * OvsAddPorts --
330  *     Add the specified destination vport into the forwarding context. If the
331  *     vport is a VIF/external port, it is added directly to the NBL. If it is
332  *     a tunneling port, it is NOT added to the NBL.
333  *
334  * Result:
335  *     NDIS_STATUS_SUCCESS on success
336  *     Other NDIS_STATUS upon failure.
337  * --------------------------------------------------------------------------
338  */
339 static __inline NDIS_STATUS
340 OvsAddPorts(OvsForwardingContext *ovsFwdCtx,
341             OvsFlowKey *flowKey,
342             NDIS_SWITCH_PORT_ID dstPortId,
343             BOOLEAN preserveVLAN,
344             BOOLEAN preservePriority)
345 {
346     POVS_VPORT_ENTRY vport;
347     PNDIS_SWITCH_PORT_DESTINATION fwdPort;
348     NDIS_STATUS status;
349     POVS_SWITCH_CONTEXT switchContext = ovsFwdCtx->switchContext;
350
351     /*
352      * We hold the dispatch lock that protects the list of vports, so vports
353      * validated here can be added as destinations safely before we call into
354      * NDIS.
355      *
356      * Some of the vports can be tunnelled ports as well in which case
357      * they should be added to a separate list of tunnelled destination ports
358      * instead of the VIF ports. The context for the tunnel is settable
359      * in OvsForwardingContext.
360      */
361     vport = OvsFindVportByPortNo(ovsFwdCtx->switchContext, dstPortId);
362     if (vport == NULL || vport->ovsState != OVS_STATE_CONNECTED) {
363         /*
364          * There may be some latency between a port disappearing, and userspace
365          * updating the recalculated flows. In the meantime, handle invalid
366          * ports gracefully.
367          */
368         ovsActionStats.noVport++;
369         return NDIS_STATUS_SUCCESS;
370     }
371     ASSERT(vport->nicState == NdisSwitchNicStateConnected);
372     vport->stats.txPackets++;
373     vport->stats.txBytes +=
374         NET_BUFFER_DATA_LENGTH(NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl));
375
376     if (OvsIsBridgeInternalVport(vport)) {
377         return NDIS_STATUS_SUCCESS;
378     }
379
380     if (OvsDetectTunnelPkt(ovsFwdCtx, vport, flowKey)) {
381         return NDIS_STATUS_SUCCESS;
382     }
383
384     if (ovsFwdCtx->destPortsSizeOut == ovsFwdCtx->destPortsSizeIn) {
385         if (ovsFwdCtx->destPortsSizeIn == 0) {
386             ASSERT(ovsFwdCtx->destinationPorts == NULL);
387             ASSERT(ovsFwdCtx->fwdDetail->NumAvailableDestinations == 0);
388             status =
389                 switchContext->NdisSwitchHandlers.GrowNetBufferListDestinations(
390                     switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
391                     OVS_DEST_PORTS_ARRAY_MIN_SIZE,
392                     &ovsFwdCtx->destinationPorts);
393             if (status != NDIS_STATUS_SUCCESS) {
394                 ovsActionStats.cannotGrowDest++;
395                 return status;
396             }
397             ovsFwdCtx->destPortsSizeIn =
398                 ovsFwdCtx->fwdDetail->NumAvailableDestinations;
399             ASSERT(ovsFwdCtx->destinationPorts);
400         } else {
401             ASSERT(ovsFwdCtx->destinationPorts != NULL);
402             /*
403              * NumElements:
404              * A ULONG value that specifies the total number of
405              * NDIS_SWITCH_PORT_DESTINATION elements in the
406              * NDIS_SWITCH_FORWARDING_DESTINATION_ARRAY structure.
407              *
408              * NumDestinations:
409              * A ULONG value that specifies the number of
410              * NDIS_SWITCH_PORT_DESTINATION elements in the
411              * NDIS_SWITCH_FORWARDING_DESTINATION_ARRAY structure that
412              * specify port destinations.
413              *
414              * NumAvailableDestinations:
415              * A value that specifies the number of unused extensible switch
416              * destination ports elements within an NET_BUFFER_LIST structure.
417              */
418             ASSERT(ovsFwdCtx->destinationPorts->NumElements ==
419                    ovsFwdCtx->destPortsSizeIn);
420             ASSERT(ovsFwdCtx->destinationPorts->NumDestinations ==
421                    ovsFwdCtx->destPortsSizeOut -
422                    ovsFwdCtx->fwdDetail->NumAvailableDestinations);
423             ASSERT(ovsFwdCtx->fwdDetail->NumAvailableDestinations > 0);
424             /*
425              * Before we grow the array of destination ports, the current set
426              * of ports needs to be committed. Only the ports added since the
427              * last commit need to be part of the new update.
428              */
429             status = switchContext->NdisSwitchHandlers.UpdateNetBufferListDestinations(
430                 switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
431                 ovsFwdCtx->fwdDetail->NumAvailableDestinations,
432                 ovsFwdCtx->destinationPorts);
433             if (status != NDIS_STATUS_SUCCESS) {
434                 ovsActionStats.cannotGrowDest++;
435                 return status;
436             }
437             ASSERT(ovsFwdCtx->destinationPorts->NumElements ==
438                    ovsFwdCtx->destPortsSizeIn);
439             ASSERT(ovsFwdCtx->destinationPorts->NumDestinations ==
440                    ovsFwdCtx->destPortsSizeOut);
441             ASSERT(ovsFwdCtx->fwdDetail->NumAvailableDestinations == 0);
442
443             status = switchContext->NdisSwitchHandlers.GrowNetBufferListDestinations(
444                 switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
445                 ovsFwdCtx->destPortsSizeIn, &ovsFwdCtx->destinationPorts);
446             if (status != NDIS_STATUS_SUCCESS) {
447                 ovsActionStats.cannotGrowDest++;
448                 return status;
449             }
450             ASSERT(ovsFwdCtx->destinationPorts != NULL);
451             ovsFwdCtx->destPortsSizeIn <<= 1;
452         }
453     }
454
455     ASSERT(ovsFwdCtx->destPortsSizeOut < ovsFwdCtx->destPortsSizeIn);
456     fwdPort =
457         NDIS_SWITCH_PORT_DESTINATION_AT_ARRAY_INDEX(ovsFwdCtx->destinationPorts,
458                                                     ovsFwdCtx->destPortsSizeOut);
459
460     fwdPort->PortId = vport->portId;
461     fwdPort->NicIndex = vport->nicIndex;
462     fwdPort->IsExcluded = 0;
463     fwdPort->PreserveVLAN = preserveVLAN;
464     fwdPort->PreservePriority = preservePriority;
465     ovsFwdCtx->destPortsSizeOut += 1;
466
467     return NDIS_STATUS_SUCCESS;
468 }
469
470
471 /*
472  * --------------------------------------------------------------------------
473  * OvsClearTunTxCtx --
474  *     Utility function to clear tx tunneling context.
475  * --------------------------------------------------------------------------
476  */
477 static __inline VOID
478 OvsClearTunTxCtx(OvsForwardingContext *ovsFwdCtx)
479 {
480     ovsFwdCtx->tunnelTxNic = NULL;
481     ovsFwdCtx->tunKey.dst = 0;
482 }
483
484
485 /*
486  * --------------------------------------------------------------------------
487  * OvsClearTunRxCtx --
488  *     Utility function to clear rx tunneling context.
489  * --------------------------------------------------------------------------
490  */
491 static __inline VOID
492 OvsClearTunRxCtx(OvsForwardingContext *ovsFwdCtx)
493 {
494     ovsFwdCtx->tunnelRxNic = NULL;
495     ovsFwdCtx->tunKey.dst = 0;
496 }
497
498
499 /*
500  * --------------------------------------------------------------------------
501  * OvsCompleteNBLForwardingCtx --
502  *     This utility function is responsible for freeing/completing an NBL - either
503  *     by adding it to a completion list or by freeing it.
504  *
505  * Side effects:
506  *     It also resets the necessary fields in 'ovsFwdCtx'.
507  * --------------------------------------------------------------------------
508  */
509 static __inline VOID
510 OvsCompleteNBLForwardingCtx(OvsForwardingContext *ovsFwdCtx,
511                             PCWSTR dropReason)
512 {
513     NDIS_STRING filterReason;
514
515     RtlInitUnicodeString(&filterReason, dropReason);
516     if (ovsFwdCtx->completionList) {
517         OvsAddPktCompletionList(ovsFwdCtx->completionList, TRUE,
518             ovsFwdCtx->fwdDetail->SourcePortId, ovsFwdCtx->curNbl, 1,
519             &filterReason);
520         ovsFwdCtx->curNbl = NULL;
521     } else {
522         /* If there is no completionList, we assume this is ovs created NBL */
523         ovsFwdCtx->curNbl = OvsCompleteNBL(ovsFwdCtx->switchContext,
524                                            ovsFwdCtx->curNbl, TRUE);
525         ASSERT(ovsFwdCtx->curNbl == NULL);
526     }
527     /* XXX: these can be made debug only to save cycles. Ideally the pipeline
528      * using these fields should reset the values at the end of the pipeline. */
529     ovsFwdCtx->destPortsSizeOut = 0;
530     ovsFwdCtx->tunnelTxNic = NULL;
531     ovsFwdCtx->tunnelRxNic = NULL;
532 }
533
534 /*
535  * --------------------------------------------------------------------------
536  * OvsDoFlowLookupOutput --
537  *     Function to be used for the second stage of a tunneling workflow, ie.:
538  *     - On the encapsulated packet on Tx path, to do a flow extract, flow
539  *       lookup and excuting the actions.
540  *     - On the decapsulated packet on Rx path, to do a flow extract, flow
541  *       lookup and excuting the actions.
542  *
543  *     XXX: It is assumed that the NBL in 'ovsFwdCtx' is owned by OVS. This is
544  *     until the new buffer management framework is adopted.
545  *
546  * Side effects:
547  *     The NBL in 'ovsFwdCtx' is consumed.
548  * --------------------------------------------------------------------------
549  */
550 static __inline NDIS_STATUS
551 OvsDoFlowLookupOutput(OvsForwardingContext *ovsFwdCtx)
552 {
553     OvsFlowKey key;
554     OvsFlow *flow;
555     UINT64 hash;
556     NDIS_STATUS status;
557     POVS_VPORT_ENTRY vport =
558         OvsFindVportByPortNo(ovsFwdCtx->switchContext, ovsFwdCtx->srcVportNo);
559     if (vport == NULL || vport->ovsState != OVS_STATE_CONNECTED) {
560         ASSERT(FALSE);  // XXX: let's catch this for now
561         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
562             L"OVS-Dropped due to internal/tunnel port removal");
563         ovsActionStats.noVport++;
564         return NDIS_STATUS_SUCCESS;
565     }
566     ASSERT(vport->nicState == NdisSwitchNicStateConnected);
567
568     /* Assert that in the Rx direction, key is always setup. */
569     ASSERT(ovsFwdCtx->tunnelRxNic == NULL || ovsFwdCtx->tunKey.dst != 0);
570     status = OvsExtractFlow(ovsFwdCtx->curNbl, ovsFwdCtx->srcVportNo,
571                           &key, &ovsFwdCtx->layers, ovsFwdCtx->tunKey.dst != 0 ?
572                                          &ovsFwdCtx->tunKey : NULL);
573     if (status != NDIS_STATUS_SUCCESS) {
574         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
575                                     L"OVS-Flow extract failed");
576         ovsActionStats.failedFlowExtract++;
577         return status;
578     }
579
580     flow = OvsLookupFlow(&ovsFwdCtx->switchContext->datapath, &key, &hash, FALSE);
581     if (flow) {
582         OvsFlowUsed(flow, ovsFwdCtx->curNbl, &ovsFwdCtx->layers);
583         ovsFwdCtx->switchContext->datapath.hits++;
584         status = OvsActionsExecute(ovsFwdCtx->switchContext,
585                                  ovsFwdCtx->completionList, ovsFwdCtx->curNbl,
586                                  ovsFwdCtx->srcVportNo, ovsFwdCtx->sendFlags,
587                                  &key, &hash, &ovsFwdCtx->layers,
588                                  flow->actions, flow->actionsLen);
589         ovsFwdCtx->curNbl = NULL;
590     } else {
591         LIST_ENTRY missedPackets;
592         UINT32 num = 0;
593         ovsFwdCtx->switchContext->datapath.misses++;
594         InitializeListHead(&missedPackets);
595         status = OvsCreateAndAddPackets(NULL, 0, OVS_PACKET_CMD_MISS,
596                           ovsFwdCtx->srcVportNo,
597                           &key,ovsFwdCtx->curNbl,
598                           ovsFwdCtx->tunnelRxNic != NULL, &ovsFwdCtx->layers,
599                           ovsFwdCtx->switchContext, &missedPackets, &num);
600         if (num) {
601             OvsQueuePackets(&missedPackets, num);
602         }
603         if (status == NDIS_STATUS_SUCCESS) {
604             /* Complete the packet since it was copied to user buffer. */
605             OvsCompleteNBLForwardingCtx(ovsFwdCtx,
606                 L"OVS-Dropped since packet was copied to userspace");
607             ovsActionStats.flowMiss++;
608             status = NDIS_STATUS_SUCCESS;
609         } else {
610             OvsCompleteNBLForwardingCtx(ovsFwdCtx,
611                 L"OVS-Dropped due to failure to queue to userspace");
612             status = NDIS_STATUS_FAILURE;
613             ovsActionStats.failedFlowMiss++;
614         }
615     }
616
617     return status;
618 }
619
620 /*
621  * --------------------------------------------------------------------------
622  * OvsTunnelPortTx --
623  *     The start function for Tx tunneling - encapsulates the packet, and
624  *     outputs the packet on the PIF bridge.
625  *
626  * Side effects:
627  *     The NBL in 'ovsFwdCtx' is consumed.
628  * --------------------------------------------------------------------------
629  */
630 static __inline NDIS_STATUS
631 OvsTunnelPortTx(OvsForwardingContext *ovsFwdCtx)
632 {
633     NDIS_STATUS status = NDIS_STATUS_FAILURE;
634     PNET_BUFFER_LIST newNbl = NULL;
635
636     /*
637      * Setup the source port to be the internal port to as to facilitate the
638      * second OvsLookupFlow.
639      */
640     if (ovsFwdCtx->switchContext->internalVport == NULL ||
641         ovsFwdCtx->switchContext->virtualExternalVport == NULL) {
642         OvsClearTunTxCtx(ovsFwdCtx);
643         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
644             L"OVS-Dropped since either internal or external port is absent");
645         return NDIS_STATUS_FAILURE;
646     }
647     ovsFwdCtx->srcVportNo =
648         ((POVS_VPORT_ENTRY)ovsFwdCtx->switchContext->internalVport)->portNo;
649
650     ovsFwdCtx->fwdDetail->SourcePortId = ovsFwdCtx->switchContext->internalPortId;
651     ovsFwdCtx->fwdDetail->SourceNicIndex =
652         ((POVS_VPORT_ENTRY)ovsFwdCtx->switchContext->internalVport)->nicIndex;
653
654     /* Do the encap. Encap function does not consume the NBL. */
655     switch(ovsFwdCtx->tunnelTxNic->ovsType) {
656     case OVS_VPORT_TYPE_VXLAN:
657         status = OvsEncapVxlan(ovsFwdCtx->curNbl, &ovsFwdCtx->tunKey,
658                                ovsFwdCtx->switchContext,
659                                &ovsFwdCtx->layers, &newNbl);
660         break;
661     case OVS_VPORT_TYPE_STT:
662         status = OvsEncapStt(ovsFwdCtx->tunnelTxNic, ovsFwdCtx->curNbl,
663                              &ovsFwdCtx->tunKey,
664                              ovsFwdCtx->switchContext,
665                              &ovsFwdCtx->layers, &newNbl);
666         break;
667     default:
668         ASSERT(! "Tx: Unhandled tunnel type");
669     }
670
671     /* Reset the tunnel context so that it doesn't get used after this point. */
672     OvsClearTunTxCtx(ovsFwdCtx);
673
674     if (status == NDIS_STATUS_SUCCESS) {
675         ASSERT(newNbl);
676         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
677                                     L"Complete after cloning NBL for encapsulation");
678         ovsFwdCtx->curNbl = newNbl;
679         status = OvsDoFlowLookupOutput(ovsFwdCtx);
680         ASSERT(ovsFwdCtx->curNbl == NULL);
681     } else {
682         /*
683         * XXX: Temporary freeing of the packet until we register a
684          * callback to IP helper.
685          */
686         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
687                                     L"OVS-Dropped due to encap failure");
688         ovsActionStats.failedEncap++;
689         status = NDIS_STATUS_SUCCESS;
690     }
691
692     return status;
693 }
694
695 /*
696  * --------------------------------------------------------------------------
697  * OvsTunnelPortRx --
698  *     Decapsulate the incoming NBL based on the tunnel type and goes through
699  *     the flow lookup for the inner packet.
700  *
701  *     Note: IP checksum is validate here, but L4 checksum validation needs
702  *     to be done by the corresponding tunnel types.
703  *
704  * Side effects:
705  *     The NBL in 'ovsFwdCtx' is consumed.
706  * --------------------------------------------------------------------------
707  */
708 static __inline NDIS_STATUS
709 OvsTunnelPortRx(OvsForwardingContext *ovsFwdCtx)
710 {
711     NDIS_STATUS status = NDIS_STATUS_SUCCESS;
712     PNET_BUFFER_LIST newNbl = NULL;
713     POVS_VPORT_ENTRY tunnelRxVport = ovsFwdCtx->tunnelRxNic;
714
715     if (OvsValidateIPChecksum(ovsFwdCtx->curNbl, &ovsFwdCtx->layers)
716             != NDIS_STATUS_SUCCESS) {
717         ovsActionStats.failedChecksum++;
718         OVS_LOG_INFO("Packet dropped due to IP checksum failure.");
719         goto dropNbl;
720     }
721
722     /*
723      * Decap port functions should return a new NBL if it was copied, and
724      * this new NBL should be setup as the ovsFwdCtx->curNbl.
725      */
726
727     switch(tunnelRxVport->ovsType) {
728     case OVS_VPORT_TYPE_VXLAN:
729         status = OvsDecapVxlan(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
730                                &ovsFwdCtx->tunKey, &newNbl);
731         break;
732     case OVS_VPORT_TYPE_STT:
733         status = OvsDecapStt(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
734                              &ovsFwdCtx->tunKey, &newNbl);
735         break;
736     default:
737         OVS_LOG_ERROR("Rx: Unhandled tunnel type: %d\n",
738                       tunnelRxVport->ovsType);
739         ASSERT(! "Rx: Unhandled tunnel type");
740         status = NDIS_STATUS_NOT_SUPPORTED;
741     }
742
743     if (status != NDIS_STATUS_SUCCESS) {
744         ovsActionStats.failedDecap++;
745         goto dropNbl;
746     }
747
748     /*
749      * tunnelRxNic and other fields will be cleared, re-init the context
750      * before usage.
751       */
752     OvsCompleteNBLForwardingCtx(ovsFwdCtx,
753                                 L"OVS-dropped due to new decap packet");
754
755     /* Decapsulated packet is in a new NBL */
756     ovsFwdCtx->tunnelRxNic = tunnelRxVport;
757     OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
758                          newNbl, tunnelRxVport->portNo, 0,
759                          NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
760                          ovsFwdCtx->completionList,
761                          &ovsFwdCtx->layers, FALSE);
762
763     /*
764      * Set the NBL's SourcePortId and SourceNicIndex to default values to
765      * keep NDIS happy when we forward the packet.
766      */
767     ovsFwdCtx->fwdDetail->SourcePortId = NDIS_SWITCH_DEFAULT_PORT_ID;
768     ovsFwdCtx->fwdDetail->SourceNicIndex = 0;
769
770     status = OvsDoFlowLookupOutput(ovsFwdCtx);
771     ASSERT(ovsFwdCtx->curNbl == NULL);
772     OvsClearTunRxCtx(ovsFwdCtx);
773
774     return status;
775
776 dropNbl:
777     OvsCompleteNBLForwardingCtx(ovsFwdCtx,
778             L"OVS-dropped due to decap failure");
779     OvsClearTunRxCtx(ovsFwdCtx);
780     return status;
781 }
782
783
784 /*
785  * --------------------------------------------------------------------------
786  * OvsOutputForwardingCtx --
787  *     This function outputs an NBL to NDIS or to a tunneling pipeline based on
788  *     the ports added so far into 'ovsFwdCtx'.
789  *
790  * Side effects:
791  *     This function consumes the NBL - either by forwarding it successfully to
792  *     NDIS, or adding it to the completion list in 'ovsFwdCtx', or freeing it.
793  *
794  *     Also makes sure that the list of destination ports - tunnel or otherwise is
795  *     drained.
796  * --------------------------------------------------------------------------
797  */
798 static __inline NDIS_STATUS
799 OvsOutputForwardingCtx(OvsForwardingContext *ovsFwdCtx)
800 {
801     NDIS_STATUS status = STATUS_SUCCESS;
802     POVS_SWITCH_CONTEXT switchContext = ovsFwdCtx->switchContext;
803     PCWSTR dropReason;
804
805     /*
806      * Handle the case where the some of the destination ports are tunneled
807      * ports - the non-tunneled ports get a unmodified copy of the NBL, and the
808      * tunneling pipeline starts when we output the packet to tunneled port.
809      */
810     if (ovsFwdCtx->destPortsSizeOut > 0) {
811         PNET_BUFFER_LIST newNbl = NULL;
812         PNET_BUFFER nb;
813         UINT32 portsToUpdate =
814             ovsFwdCtx->fwdDetail->NumAvailableDestinations -
815             (ovsFwdCtx->destPortsSizeIn - ovsFwdCtx->destPortsSizeOut);
816
817         ASSERT(ovsFwdCtx->destinationPorts != NULL);
818
819         /*
820          * Create a copy of the packet in order to do encap on it later. Also,
821          * don't copy the offload context since the encap'd packet has a
822          * different set of headers. This will change when we implement offloads
823          * before doing encapsulation.
824          */
825         if (ovsFwdCtx->tunnelTxNic != NULL || ovsFwdCtx->tunnelRxNic != NULL) {
826             nb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
827             newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
828                                        0, 0, TRUE /*copy NBL info*/);
829             if (newNbl == NULL) {
830                 status = NDIS_STATUS_RESOURCES;
831                 ovsActionStats.noCopiedNbl++;
832                 dropReason = L"Dropped due to failure to create NBL copy.";
833                 goto dropit;
834             }
835         }
836
837         /* It does not seem like we'll get here unless 'portsToUpdate' > 0. */
838         ASSERT(portsToUpdate > 0);
839         status = switchContext->NdisSwitchHandlers.UpdateNetBufferListDestinations(
840             switchContext->NdisSwitchContext, ovsFwdCtx->curNbl,
841             portsToUpdate, ovsFwdCtx->destinationPorts);
842         if (status != NDIS_STATUS_SUCCESS) {
843             OvsCompleteNBL(ovsFwdCtx->switchContext, newNbl, TRUE);
844             ovsActionStats.cannotGrowDest++;
845             dropReason = L"Dropped due to failure to update destinations.";
846             goto dropit;
847         }
848
849         OvsSendNBLIngress(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
850                           ovsFwdCtx->sendFlags);
851         /* End this pipeline by resetting the corresponding context. */
852         ovsFwdCtx->destPortsSizeOut = 0;
853         ovsFwdCtx->curNbl = NULL;
854         if (newNbl) {
855             status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
856                                           newNbl, ovsFwdCtx->srcVportNo, 0,
857                                           NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
858                                           ovsFwdCtx->completionList,
859                                           &ovsFwdCtx->layers, FALSE);
860             if (status != NDIS_STATUS_SUCCESS) {
861                 dropReason = L"Dropped due to resouces.";
862                 goto dropit;
863             }
864         }
865     }
866
867     if (ovsFwdCtx->tunnelTxNic != NULL) {
868         status = OvsTunnelPortTx(ovsFwdCtx);
869         ASSERT(ovsFwdCtx->tunnelTxNic == NULL);
870         ASSERT(ovsFwdCtx->tunKey.dst == 0);
871     } else if (ovsFwdCtx->tunnelRxNic != NULL) {
872         status = OvsTunnelPortRx(ovsFwdCtx);
873         ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
874         ASSERT(ovsFwdCtx->tunKey.dst == 0);
875     }
876     ASSERT(ovsFwdCtx->curNbl == NULL);
877
878     return status;
879
880 dropit:
881     if (status != NDIS_STATUS_SUCCESS) {
882         OvsCompleteNBLForwardingCtx(ovsFwdCtx, dropReason);
883     }
884
885     return status;
886 }
887
888
889 /*
890  * --------------------------------------------------------------------------
891  * OvsLookupFlowOutput --
892  *     Utility function for external callers to do flow extract, lookup,
893  *     actions execute on a given NBL.
894  *
895  *     Note: If this is being used from a callback function, make sure that the
896  *     arguments specified are still valid in the asynchronous context.
897  *
898  * Side effects:
899  *     This function consumes the NBL.
900  * --------------------------------------------------------------------------
901  */
902 VOID
903 OvsLookupFlowOutput(POVS_SWITCH_CONTEXT switchContext,
904                     VOID *compList,
905                     PNET_BUFFER_LIST curNbl)
906 {
907     NDIS_STATUS status;
908     OvsForwardingContext ovsFwdCtx;
909     POVS_VPORT_ENTRY internalVport =
910         (POVS_VPORT_ENTRY)switchContext->internalVport;
911
912     /* XXX: make sure comp list was not a stack variable previously. */
913     OvsCompletionList *completionList = (OvsCompletionList *)compList;
914
915     /*
916      * XXX: can internal port disappear while we are busy doing ARP resolution?
917      * It could, but will we get this callback from IP helper in that case. Need
918      * to check.
919      */
920     ASSERT(switchContext->internalVport);
921     status = OvsInitForwardingCtx(&ovsFwdCtx, switchContext, curNbl,
922                                   internalVport->portNo, 0,
923                                   NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(curNbl),
924                                   completionList, NULL, TRUE);
925     if (status != NDIS_STATUS_SUCCESS) {
926         OvsCompleteNBLForwardingCtx(&ovsFwdCtx,
927                                     L"OVS-Dropped due to resources");
928         return;
929     }
930
931     ASSERT(FALSE);
932     /*
933      * XXX: We need to acquire the dispatch lock and the datapath lock.
934      */
935
936     OvsDoFlowLookupOutput(&ovsFwdCtx);
937 }
938
939
940 /*
941  * --------------------------------------------------------------------------
942  * OvsOutputBeforeSetAction --
943  *     Function to be called to complete one set of actions on an NBL, before
944  *     we start the next one.
945  * --------------------------------------------------------------------------
946  */
947 static __inline NDIS_STATUS
948 OvsOutputBeforeSetAction(OvsForwardingContext *ovsFwdCtx)
949 {
950     PNET_BUFFER_LIST newNbl;
951     NDIS_STATUS status = NDIS_STATUS_SUCCESS;
952     PNET_BUFFER nb;
953
954     /*
955      * Create a copy and work on the copy after this point. The original NBL is
956      * forwarded. One reason to not use the copy for forwarding is that
957      * ports have already been added to the original NBL, and it might be
958      * inefficient/impossible to remove/re-add them to the copy. There's no
959      * notion of removing the ports, the ports need to be marked as
960      * "isExcluded". There's seems no real advantage to retaining the original
961      * and sending out the copy instead.
962      *
963      * XXX: We are copying the offload context here. This is to handle actions
964      * such as:
965      * outport, pop_vlan(), outport, push_vlan(), outport
966      *
967      * copy size needs to include inner ether + IP + TCP, need to revisit
968      * if we support IP options.
969      * XXX Head room needs to include the additional encap.
970      * XXX copySize check is not considering multiple NBs.
971      */
972     nb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
973     newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
974                                0, 0, TRUE /*copy NBL info*/);
975
976     ASSERT(ovsFwdCtx->destPortsSizeOut > 0 ||
977            ovsFwdCtx->tunnelTxNic != NULL || ovsFwdCtx->tunnelRxNic != NULL);
978
979     /* Send the original packet out */
980     status = OvsOutputForwardingCtx(ovsFwdCtx);
981     ASSERT(ovsFwdCtx->curNbl == NULL);
982     ASSERT(ovsFwdCtx->destPortsSizeOut == 0);
983     ASSERT(ovsFwdCtx->tunnelRxNic == NULL);
984     ASSERT(ovsFwdCtx->tunnelTxNic == NULL);
985
986     /* If we didn't make a copy, can't continue. */
987     if (newNbl == NULL) {
988         ovsActionStats.noCopiedNbl++;
989         return NDIS_STATUS_RESOURCES;
990     }
991
992     /* Finish the remaining actions with the new NBL */
993     if (status != NDIS_STATUS_SUCCESS) {
994         OvsCompleteNBL(ovsFwdCtx->switchContext, newNbl, TRUE);
995     } else {
996         status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
997                                       newNbl, ovsFwdCtx->srcVportNo, 0,
998                                       NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
999                                       ovsFwdCtx->completionList,
1000                                       &ovsFwdCtx->layers, FALSE);
1001     }
1002
1003     return status;
1004 }
1005
1006
1007 /*
1008  * --------------------------------------------------------------------------
1009  * OvsPopVlanInPktBuf --
1010  *     Function to pop a VLAN tag when the tag is in the packet buffer.
1011  * --------------------------------------------------------------------------
1012  */
1013 static __inline NDIS_STATUS
1014 OvsPopVlanInPktBuf(OvsForwardingContext *ovsFwdCtx)
1015 {
1016     PNET_BUFFER curNb;
1017     PMDL curMdl;
1018     PUINT8 bufferStart;
1019     ULONG dataLength = sizeof (DL_EUI48) + sizeof (DL_EUI48);
1020     UINT32 packetLen, mdlLen;
1021     PNET_BUFFER_LIST newNbl;
1022     NDIS_STATUS status;
1023
1024     /*
1025      * Declare a dummy vlanTag structure since we need to compute the size
1026      * of shiftLength. The NDIS one is a unionized structure.
1027      */
1028     NDIS_PACKET_8021Q_INFO vlanTag = {0};
1029     ULONG shiftLength = sizeof (vlanTag.TagHeader);
1030     PUINT8 tempBuffer[sizeof (DL_EUI48) + sizeof (DL_EUI48)];
1031
1032     newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
1033                                0, 0, TRUE /* copy NBL info */);
1034     if (!newNbl) {
1035         ovsActionStats.noCopiedNbl++;
1036         return NDIS_STATUS_RESOURCES;
1037     }
1038
1039     /* Complete the original NBL and create a copy to modify. */
1040     OvsCompleteNBLForwardingCtx(ovsFwdCtx, L"OVS-Dropped due to copy");
1041
1042     status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
1043                                   newNbl, ovsFwdCtx->srcVportNo, 0,
1044                                   NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
1045                                   NULL, &ovsFwdCtx->layers, FALSE);
1046     if (status != NDIS_STATUS_SUCCESS) {
1047         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
1048                                     L"Dropped due to resouces");
1049         return NDIS_STATUS_RESOURCES;
1050     }
1051
1052     curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
1053     packetLen = NET_BUFFER_DATA_LENGTH(curNb);
1054     ASSERT(curNb->Next == NULL);
1055     curMdl = NET_BUFFER_CURRENT_MDL(curNb);
1056     NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
1057     if (!bufferStart) {
1058         return NDIS_STATUS_RESOURCES;
1059     }
1060     mdlLen -= NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
1061     /* Bail out if L2 + VLAN header is not contiguous in the first buffer. */
1062     if (MIN(packetLen, mdlLen) < sizeof (EthHdr) + shiftLength) {
1063         ASSERT(FALSE);
1064         return NDIS_STATUS_FAILURE;
1065     }
1066     bufferStart += NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
1067     RtlCopyMemory(tempBuffer, bufferStart, dataLength);
1068     RtlCopyMemory(bufferStart + shiftLength, tempBuffer, dataLength);
1069     NdisAdvanceNetBufferDataStart(curNb, shiftLength, FALSE, NULL);
1070
1071     return NDIS_STATUS_SUCCESS;
1072 }
1073
1074 /*
1075  * --------------------------------------------------------------------------
1076  * OvsTunnelAttrToIPv4TunnelKey --
1077  *      Convert tunnel attribute to OvsIPv4TunnelKey.
1078  * --------------------------------------------------------------------------
1079  */
1080 static __inline NDIS_STATUS
1081 OvsTunnelAttrToIPv4TunnelKey(PNL_ATTR attr,
1082                              OvsIPv4TunnelKey *tunKey)
1083 {
1084    PNL_ATTR a;
1085    INT rem;
1086
1087    tunKey->attr[0] = 0;
1088    tunKey->attr[1] = 0;
1089    tunKey->attr[2] = 0;
1090    ASSERT(NlAttrType(attr) == OVS_KEY_ATTR_TUNNEL);
1091
1092    NL_ATTR_FOR_EACH_UNSAFE (a, rem, NlAttrData(attr),
1093                             NlAttrGetSize(attr)) {
1094       switch (NlAttrType(a)) {
1095       case OVS_TUNNEL_KEY_ATTR_ID:
1096          tunKey->tunnelId = NlAttrGetBe64(a);
1097          tunKey->flags |= OVS_TNL_F_KEY;
1098          break;
1099       case OVS_TUNNEL_KEY_ATTR_IPV4_SRC:
1100          tunKey->src = NlAttrGetBe32(a);
1101          break;
1102       case OVS_TUNNEL_KEY_ATTR_IPV4_DST:
1103          tunKey->dst = NlAttrGetBe32(a);
1104          break;
1105       case OVS_TUNNEL_KEY_ATTR_TOS:
1106          tunKey->tos = NlAttrGetU8(a);
1107          break;
1108       case OVS_TUNNEL_KEY_ATTR_TTL:
1109          tunKey->ttl = NlAttrGetU8(a);
1110          break;
1111       case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT:
1112          tunKey->flags |= OVS_TNL_F_DONT_FRAGMENT;
1113          break;
1114       case OVS_TUNNEL_KEY_ATTR_CSUM:
1115          tunKey->flags |= OVS_TNL_F_CSUM;
1116          break;
1117       default:
1118          ASSERT(0);
1119       }
1120    }
1121
1122    return NDIS_STATUS_SUCCESS;
1123 }
1124
1125 /*
1126  *----------------------------------------------------------------------------
1127  * OvsUpdateEthHeader --
1128  *      Updates the ethernet header in ovsFwdCtx.curNbl inline based on the
1129  *      specified key.
1130  *----------------------------------------------------------------------------
1131  */
1132 static __inline NDIS_STATUS
1133 OvsUpdateEthHeader(OvsForwardingContext *ovsFwdCtx,
1134                    const struct ovs_key_ethernet *ethAttr)
1135 {
1136     PNET_BUFFER curNb;
1137     PMDL curMdl;
1138     PUINT8 bufferStart;
1139     EthHdr *ethHdr;
1140     UINT32 packetLen, mdlLen;
1141
1142     curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
1143     ASSERT(curNb->Next == NULL);
1144     packetLen = NET_BUFFER_DATA_LENGTH(curNb);
1145     curMdl = NET_BUFFER_CURRENT_MDL(curNb);
1146     NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
1147     if (!bufferStart) {
1148         ovsActionStats.noResource++;
1149         return NDIS_STATUS_RESOURCES;
1150     }
1151     mdlLen -= NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
1152     ASSERT(mdlLen > 0);
1153     /* Bail out if the L2 header is not in a contiguous buffer. */
1154     if (MIN(packetLen, mdlLen) < sizeof *ethHdr) {
1155         ASSERT(FALSE);
1156         return NDIS_STATUS_FAILURE;
1157     }
1158     ethHdr = (EthHdr *)(bufferStart + NET_BUFFER_CURRENT_MDL_OFFSET(curNb));
1159
1160     RtlCopyMemory(ethHdr->Destination, ethAttr->eth_dst,
1161                    sizeof ethHdr->Destination);
1162     RtlCopyMemory(ethHdr->Source, ethAttr->eth_src, sizeof ethHdr->Source);
1163
1164     return NDIS_STATUS_SUCCESS;
1165 }
1166
1167 /*
1168  *----------------------------------------------------------------------------
1169  * OvsUpdateIPv4Header --
1170  *      Updates the IPv4 header in ovsFwdCtx.curNbl inline based on the
1171  *      specified key.
1172  *----------------------------------------------------------------------------
1173  */
1174 static __inline NDIS_STATUS
1175 OvsUpdateIPv4Header(OvsForwardingContext *ovsFwdCtx,
1176                     const struct ovs_key_ipv4 *ipAttr)
1177 {
1178     PNET_BUFFER curNb;
1179     PMDL curMdl;
1180     ULONG curMdlOffset;
1181     PUINT8 bufferStart;
1182     UINT32 mdlLen, hdrSize, packetLen;
1183     OVS_PACKET_HDR_INFO *layers = &ovsFwdCtx->layers;
1184     NDIS_STATUS status;
1185     IPHdr *ipHdr;
1186     TCPHdr *tcpHdr = NULL;
1187     UDPHdr *udpHdr = NULL;
1188
1189     ASSERT(layers->value != 0);
1190
1191     /*
1192      * Peek into the MDL to get a handle to the IP header and if required
1193      * the TCP/UDP header as well. We check if the required headers are in one
1194      * contiguous MDL, and if not, we copy them over to one MDL.
1195      */
1196     curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
1197     ASSERT(curNb->Next == NULL);
1198     packetLen = NET_BUFFER_DATA_LENGTH(curNb);
1199     curMdl = NET_BUFFER_CURRENT_MDL(curNb);
1200     NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
1201     if (!bufferStart) {
1202         ovsActionStats.noResource++;
1203         return NDIS_STATUS_RESOURCES;
1204     }
1205     curMdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
1206     mdlLen -= curMdlOffset;
1207     ASSERT((INT)mdlLen >= 0);
1208
1209     if (layers->isTcp || layers->isUdp) {
1210         hdrSize = layers->l4Offset +
1211                   layers->isTcp ? sizeof (*tcpHdr) : sizeof (*udpHdr);
1212     } else {
1213         hdrSize = layers->l3Offset + sizeof (*ipHdr);
1214     }
1215
1216     /* Count of number of bytes of valid data there are in the first MDL. */
1217     mdlLen = MIN(packetLen, mdlLen);
1218     if (mdlLen < hdrSize) {
1219         PNET_BUFFER_LIST newNbl;
1220         newNbl = OvsPartialCopyNBL(ovsFwdCtx->switchContext, ovsFwdCtx->curNbl,
1221                                    hdrSize, 0, TRUE /*copy NBL info*/);
1222         if (!newNbl) {
1223             ovsActionStats.noCopiedNbl++;
1224             return NDIS_STATUS_RESOURCES;
1225         }
1226         OvsCompleteNBLForwardingCtx(ovsFwdCtx,
1227                                     L"Complete after partial copy.");
1228
1229         status = OvsInitForwardingCtx(ovsFwdCtx, ovsFwdCtx->switchContext,
1230                                       newNbl, ovsFwdCtx->srcVportNo, 0,
1231                                       NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(newNbl),
1232                                       NULL, &ovsFwdCtx->layers, FALSE);
1233         if (status != NDIS_STATUS_SUCCESS) {
1234             OvsCompleteNBLForwardingCtx(ovsFwdCtx,
1235                                         L"OVS-Dropped due to resources");
1236             return NDIS_STATUS_RESOURCES;
1237         }
1238
1239         curNb = NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx->curNbl);
1240         ASSERT(curNb->Next == NULL);
1241         curMdl = NET_BUFFER_CURRENT_MDL(curNb);
1242         NdisQueryMdl(curMdl, &bufferStart, &mdlLen, LowPagePriority);
1243         if (!curMdl) {
1244             ovsActionStats.noResource++;
1245             return NDIS_STATUS_RESOURCES;
1246         }
1247         curMdlOffset = NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
1248         mdlLen -= curMdlOffset;
1249         ASSERT(mdlLen >= hdrSize);
1250     }
1251
1252     ipHdr = (IPHdr *)(bufferStart + curMdlOffset + layers->l3Offset);
1253
1254     if (layers->isTcp) {
1255         tcpHdr = (TCPHdr *)(bufferStart + curMdlOffset + layers->l4Offset);
1256     } else if (layers->isUdp) {
1257         udpHdr = (UDPHdr *)(bufferStart + curMdlOffset + layers->l4Offset);
1258     }
1259
1260     /*
1261      * Adjust the IP header inline as dictated by the action, nad also update
1262      * the IP and the TCP checksum for the data modified.
1263      *
1264      * In the future, this could be optimized to make one call to
1265      * ChecksumUpdate32(). Ignoring this for now, since for the most common
1266      * case, we only update the TTL.
1267      */
1268     if (ipHdr->saddr != ipAttr->ipv4_src) {
1269         if (tcpHdr) {
1270             tcpHdr->check = ChecksumUpdate32(tcpHdr->check, ipHdr->saddr,
1271                                              ipAttr->ipv4_src);
1272         } else if (udpHdr && udpHdr->check) {
1273             udpHdr->check = ChecksumUpdate32(udpHdr->check, ipHdr->saddr,
1274                                              ipAttr->ipv4_src);
1275         }
1276
1277         if (ipHdr->check != 0) {
1278             ipHdr->check = ChecksumUpdate32(ipHdr->check, ipHdr->saddr,
1279                                             ipAttr->ipv4_src);
1280         }
1281         ipHdr->saddr = ipAttr->ipv4_src;
1282     }
1283     if (ipHdr->daddr != ipAttr->ipv4_dst) {
1284         if (tcpHdr) {
1285             tcpHdr->check = ChecksumUpdate32(tcpHdr->check, ipHdr->daddr,
1286                                              ipAttr->ipv4_dst);
1287         } else if (udpHdr && udpHdr->check) {
1288             udpHdr->check = ChecksumUpdate32(udpHdr->check, ipHdr->daddr,
1289                                              ipAttr->ipv4_dst);
1290         }
1291
1292         if (ipHdr->check != 0) {
1293             ipHdr->check = ChecksumUpdate32(ipHdr->check, ipHdr->daddr,
1294                                             ipAttr->ipv4_dst);
1295         }
1296         ipHdr->daddr = ipAttr->ipv4_dst;
1297     }
1298     if (ipHdr->protocol != ipAttr->ipv4_proto) {
1299         UINT16 oldProto = (ipHdr->protocol << 16) & 0xff00;
1300         UINT16 newProto = (ipAttr->ipv4_proto << 16) & 0xff00;
1301         if (tcpHdr) {
1302             tcpHdr->check = ChecksumUpdate16(tcpHdr->check, oldProto, newProto);
1303         } else if (udpHdr && udpHdr->check) {
1304             udpHdr->check = ChecksumUpdate16(udpHdr->check, oldProto, newProto);
1305         }
1306
1307         if (ipHdr->check != 0) {
1308             ipHdr->check = ChecksumUpdate16(ipHdr->check, oldProto, newProto);
1309         }
1310         ipHdr->protocol = ipAttr->ipv4_proto;
1311     }
1312     if (ipHdr->ttl != ipAttr->ipv4_ttl) {
1313         UINT16 oldTtl = (ipHdr->ttl) & 0xff;
1314         UINT16 newTtl = (ipAttr->ipv4_ttl) & 0xff;
1315         if (ipHdr->check != 0) {
1316             ipHdr->check = ChecksumUpdate16(ipHdr->check, oldTtl, newTtl);
1317         }
1318         ipHdr->ttl = ipAttr->ipv4_ttl;
1319     }
1320
1321     return NDIS_STATUS_SUCCESS;
1322 }
1323
1324 /*
1325  * --------------------------------------------------------------------------
1326  * OvsExecuteSetAction --
1327  *      Executes a set() action, but storing the actions into 'ovsFwdCtx'
1328  * --------------------------------------------------------------------------
1329  */
1330 static __inline NDIS_STATUS
1331 OvsExecuteSetAction(OvsForwardingContext *ovsFwdCtx,
1332                     OvsFlowKey *key,
1333                     UINT64 *hash,
1334                     const PNL_ATTR a)
1335 {
1336     enum ovs_key_attr type = NlAttrType(a);
1337     NDIS_STATUS status = NDIS_STATUS_SUCCESS;
1338
1339     switch (type) {
1340     case OVS_KEY_ATTR_ETHERNET:
1341         status = OvsUpdateEthHeader(ovsFwdCtx,
1342             NlAttrGetUnspec(a, sizeof(struct ovs_key_ethernet)));
1343         break;
1344
1345     case OVS_KEY_ATTR_IPV4:
1346         status = OvsUpdateIPv4Header(ovsFwdCtx,
1347             NlAttrGetUnspec(a, sizeof(struct ovs_key_ipv4)));
1348         break;
1349
1350     case OVS_KEY_ATTR_TUNNEL:
1351     {
1352         OvsIPv4TunnelKey tunKey;
1353         status = OvsTunnelAttrToIPv4TunnelKey((PNL_ATTR)a, &tunKey);
1354         ASSERT(status == NDIS_STATUS_SUCCESS);
1355         tunKey.flow_hash = (uint16)(hash ? *hash : OvsHashFlow(key));
1356         tunKey.dst_port = key->ipKey.l4.tpDst;
1357         RtlCopyMemory(&ovsFwdCtx->tunKey, &tunKey, sizeof ovsFwdCtx->tunKey);
1358         break;
1359     }
1360     case OVS_KEY_ATTR_SKB_MARK:
1361     /* XXX: Not relevant to Hyper-V. Return OK */
1362     break;
1363     case OVS_KEY_ATTR_UNSPEC:
1364     case OVS_KEY_ATTR_ENCAP:
1365     case OVS_KEY_ATTR_ETHERTYPE:
1366     case OVS_KEY_ATTR_IN_PORT:
1367     case OVS_KEY_ATTR_VLAN:
1368     case OVS_KEY_ATTR_ICMP:
1369     case OVS_KEY_ATTR_ICMPV6:
1370     case OVS_KEY_ATTR_ARP:
1371     case OVS_KEY_ATTR_ND:
1372     case __OVS_KEY_ATTR_MAX:
1373     default:
1374     OVS_LOG_INFO("Unhandled attribute %#x", type);
1375     ASSERT(FALSE);
1376     }
1377     return status;
1378 }
1379
1380 /*
1381  * --------------------------------------------------------------------------
1382  * OvsActionsExecute --
1383  *     Interpret and execute the specified 'actions' on the specifed packet
1384  *     'curNbl'. The expectation is that if the packet needs to be dropped
1385  *     (completed) for some reason, it is added to 'completionList' so that the
1386  *     caller can complete the packet. If 'completionList' is NULL, the NBL is
1387  *     assumed to be generated by OVS and freed up. Otherwise, the function
1388  *     consumes the NBL by generating a NDIS send indication for the packet.
1389  *
1390  *     There are one or more of "clone" NBLs that may get generated while
1391  *     executing the actions. Upon any failures, the "cloned" NBLs are freed up,
1392  *     and the caller does not have to worry about them.
1393  *
1394  *     Success or failure is returned based on whether the specified actions
1395  *     were executed successfully on the packet or not.
1396  * --------------------------------------------------------------------------
1397  */
1398 NDIS_STATUS
1399 OvsActionsExecute(POVS_SWITCH_CONTEXT switchContext,
1400                   OvsCompletionList *completionList,
1401                   PNET_BUFFER_LIST curNbl,
1402                   UINT32 portNo,
1403                   ULONG sendFlags,
1404                   OvsFlowKey *key,
1405                   UINT64 *hash,
1406                   OVS_PACKET_HDR_INFO *layers,
1407                   const PNL_ATTR actions,
1408                   INT actionsLen)
1409 {
1410     PNL_ATTR a;
1411     INT rem;
1412     UINT32 dstPortID;
1413     OvsForwardingContext ovsFwdCtx;
1414     PCWSTR dropReason = L"";
1415     NDIS_STATUS status;
1416     PNDIS_SWITCH_FORWARDING_DETAIL_NET_BUFFER_LIST_INFO fwdDetail =
1417         NET_BUFFER_LIST_SWITCH_FORWARDING_DETAIL(curNbl);
1418
1419     /* XXX: ASSERT that the flow table lock is held. */
1420     status = OvsInitForwardingCtx(&ovsFwdCtx, switchContext, curNbl, portNo,
1421                                   sendFlags, fwdDetail, completionList,
1422                                   layers, TRUE);
1423     if (status != NDIS_STATUS_SUCCESS) {
1424         dropReason = L"OVS-initing destination port list failed";
1425         goto dropit;
1426     }
1427
1428     if (actionsLen == 0) {
1429         dropReason = L"OVS-Dropped due to Flow action";
1430         ovsActionStats.zeroActionLen++;
1431         goto dropit;
1432     }
1433
1434     NL_ATTR_FOR_EACH_UNSAFE (a, rem, actions, actionsLen) {
1435         switch(NlAttrType(a)) {
1436         case OVS_ACTION_ATTR_OUTPUT:
1437             dstPortID = NlAttrGetU32(a);
1438             status = OvsAddPorts(&ovsFwdCtx, key, dstPortID,
1439                                               TRUE, TRUE);
1440             if (status != NDIS_STATUS_SUCCESS) {
1441                 dropReason = L"OVS-adding destination port failed";
1442                 goto dropit;
1443             }
1444             break;
1445
1446         case OVS_ACTION_ATTR_PUSH_VLAN:
1447         {
1448             struct ovs_action_push_vlan *vlan;
1449             PVOID vlanTagValue;
1450             PNDIS_NET_BUFFER_LIST_8021Q_INFO vlanTag;
1451
1452             if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
1453                 || ovsFwdCtx.tunnelRxNic != NULL) {
1454                 status = OvsOutputBeforeSetAction(&ovsFwdCtx);
1455                 if (status != NDIS_STATUS_SUCCESS) {
1456                     dropReason = L"OVS-adding destination failed";
1457                     goto dropit;
1458                 }
1459             }
1460
1461             vlanTagValue = NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
1462                                                 Ieee8021QNetBufferListInfo);
1463             if (vlanTagValue != NULL) {
1464                 /*
1465                  * XXX: We don't support double VLAN tag offload. In such cases,
1466                  * we need to insert the existing one into the packet buffer,
1467                  * and add the new one as offload. This will take care of
1468                  * guest tag-in-tag case as well as OVS rules that specify
1469                  * tag-in-tag.
1470                  */
1471             } else {
1472                  vlanTagValue = 0;
1473                  vlanTag = (PNDIS_NET_BUFFER_LIST_8021Q_INFO)(PVOID *)&vlanTagValue;
1474                  vlan = (struct ovs_action_push_vlan *)NlAttrGet((const PNL_ATTR)a);
1475                  vlanTag->TagHeader.VlanId = ntohs(vlan->vlan_tci) & 0xfff;
1476                  vlanTag->TagHeader.UserPriority = ntohs(vlan->vlan_tci) >> 13;
1477
1478                  NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
1479                                       Ieee8021QNetBufferListInfo) = vlanTagValue;
1480             }
1481             break;
1482         }
1483
1484         case OVS_ACTION_ATTR_POP_VLAN:
1485         {
1486             if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
1487                 || ovsFwdCtx.tunnelRxNic != NULL) {
1488                 status = OvsOutputBeforeSetAction(&ovsFwdCtx);
1489                 if (status != NDIS_STATUS_SUCCESS) {
1490                     dropReason = L"OVS-adding destination failed";
1491                     goto dropit;
1492                 }
1493             }
1494
1495             if (NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
1496                                      Ieee8021QNetBufferListInfo) != 0) {
1497                 NET_BUFFER_LIST_INFO(ovsFwdCtx.curNbl,
1498                                      Ieee8021QNetBufferListInfo) = 0;
1499             } else {
1500                 /*
1501                  * The VLAN tag is inserted into the packet buffer. Pop the tag
1502                  * by packet buffer modification.
1503                  */
1504                 status = OvsPopVlanInPktBuf(&ovsFwdCtx);
1505                 if (status != NDIS_STATUS_SUCCESS) {
1506                     dropReason = L"OVS-pop vlan action failed";
1507                     goto dropit;
1508                 }
1509             }
1510             break;
1511         }
1512
1513         case OVS_ACTION_ATTR_USERSPACE:
1514         {
1515             PNL_ATTR userdataAttr;
1516             PNL_ATTR queueAttr;
1517             POVS_PACKET_QUEUE_ELEM elem;
1518             BOOLEAN isRecv = FALSE;
1519
1520             POVS_VPORT_ENTRY vport = OvsFindVportByPortNo(switchContext,
1521                 portNo);
1522
1523             if (vport) {
1524                 if (vport->isExternal ||
1525                     OvsIsTunnelVportType(vport->ovsType)) {
1526                     isRecv = TRUE;
1527                 }
1528             }
1529
1530             queueAttr = NlAttrFindNested(a, OVS_USERSPACE_ATTR_PID);
1531             userdataAttr = NlAttrFindNested(a, OVS_USERSPACE_ATTR_USERDATA);
1532
1533             elem = OvsCreateQueueNlPacket((PVOID)userdataAttr,
1534                                     userdataAttr->nlaLen,
1535                                     OVS_PACKET_CMD_ACTION,
1536                                     portNo, key,ovsFwdCtx.curNbl,
1537                                     NET_BUFFER_LIST_FIRST_NB(ovsFwdCtx.curNbl),
1538                                     isRecv,
1539                                     layers);
1540             if (elem) {
1541                 LIST_ENTRY missedPackets;
1542                 InitializeListHead(&missedPackets);
1543                 InsertTailList(&missedPackets, &elem->link);
1544                 OvsQueuePackets(&missedPackets, 1);
1545                 dropReason = L"OVS-Completed since packet was copied to "
1546                              L"userspace";
1547             } else {
1548                 dropReason = L"OVS-Dropped due to failure to queue to "
1549                              L"userspace";
1550                 goto dropit;
1551             }
1552             break;
1553         }
1554         case OVS_ACTION_ATTR_SET:
1555         {
1556             if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
1557                 || ovsFwdCtx.tunnelRxNic != NULL) {
1558                 status = OvsOutputBeforeSetAction(&ovsFwdCtx);
1559                 if (status != NDIS_STATUS_SUCCESS) {
1560                     dropReason = L"OVS-adding destination failed";
1561                     goto dropit;
1562                 }
1563             }
1564
1565             status = OvsExecuteSetAction(&ovsFwdCtx, key, hash,
1566                                          (const PNL_ATTR)NlAttrGet
1567                                          ((const PNL_ATTR)a));
1568             if (status != NDIS_STATUS_SUCCESS) {
1569                 dropReason = L"OVS-set action failed";
1570                 goto dropit;
1571             }
1572             break;
1573         }
1574         case OVS_ACTION_ATTR_SAMPLE:
1575         default:
1576             status = NDIS_STATUS_NOT_SUPPORTED;
1577             break;
1578         }
1579     }
1580
1581     if (ovsFwdCtx.destPortsSizeOut > 0 || ovsFwdCtx.tunnelTxNic != NULL
1582         || ovsFwdCtx.tunnelRxNic != NULL) {
1583         status = OvsOutputForwardingCtx(&ovsFwdCtx);
1584         ASSERT(ovsFwdCtx.curNbl == NULL);
1585     }
1586
1587     ASSERT(ovsFwdCtx.destPortsSizeOut == 0);
1588     ASSERT(ovsFwdCtx.tunnelRxNic == NULL);
1589     ASSERT(ovsFwdCtx.tunnelTxNic == NULL);
1590
1591 dropit:
1592     /*
1593      * If curNbl != NULL, it implies the NBL has not been not freed up so far.
1594      */
1595     if (ovsFwdCtx.curNbl) {
1596         OvsCompleteNBLForwardingCtx(&ovsFwdCtx, dropReason);
1597     }
1598
1599     return status;
1600 }