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