datapath-windows: Fixed spelling errors in OVS
[cascardo/ovs.git] / datapath-windows / ovsext / Vxlan.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 #include "Atomic.h"
19 #include "NetProto.h"
20 #include "Switch.h"
21 #include "Vport.h"
22 #include "Flow.h"
23 #include "Vxlan.h"
24 #include "IpHelper.h"
25 #include "Checksum.h"
26 #include "User.h"
27 #include "PacketIO.h"
28 #include "Flow.h"
29 #include "PacketParser.h"
30
31 #pragma warning( push )
32 #pragma warning( disable:4127 )
33
34
35 #ifdef OVS_DBG_MOD
36 #undef OVS_DBG_MOD
37 #endif
38 #define OVS_DBG_MOD OVS_DBG_VXLAN
39 #include "Debug.h"
40
41 /* Helper macro to check if a VXLAN ID is valid. */
42 #define VXLAN_ID_IS_VALID(vxlanID) (0 < (vxlanID) && (vxlanID) <= 0xffffff)
43 #define VXLAN_TUNNELID_TO_VNI(_tID)   (UINT32)(((UINT64)(_tID)) >> 40)
44 #define VXLAN_VNI_TO_TUNNELID(_vni) (((UINT64)(_vni)) << 40)
45 #define IP_DF_NBO 0x0040
46 #define VXLAN_DEFAULT_TTL 64
47 #define VXLAN_MULTICAST_TTL 64
48 #define VXLAN_DEFAULT_INSTANCE_ID 1
49
50 /* Move to a header file */
51 extern POVS_SWITCH_CONTEXT gOvsSwitchContext;
52
53 /*
54  *----------------------------------------------------------------------------
55  * This function verifies if the VXLAN tunnel already exists, in order to
56  * avoid sending a duplicate request to the WFP base filtering engine.
57  *----------------------------------------------------------------------------
58  */
59 static BOOLEAN
60 OvsIsTunnelFilterCreated(POVS_SWITCH_CONTEXT switchContext,
61                          UINT16 udpPortDest)
62 {
63     for (UINT hash = 0; hash < OVS_MAX_VPORT_ARRAY_SIZE; hash++) {
64         PLIST_ENTRY head, link, next;
65
66         head = &(switchContext->portNoHashArray[hash & OVS_VPORT_MASK]);
67         LIST_FORALL_SAFE(head, link, next) {
68             POVS_VPORT_ENTRY vport = NULL;
69             POVS_VXLAN_VPORT vxlanPort = NULL;
70             vport = CONTAINING_RECORD(link, OVS_VPORT_ENTRY, portNoLink);
71             vxlanPort = (POVS_VXLAN_VPORT)vport->priv;
72             if (vxlanPort) {
73                 if ((udpPortDest == vxlanPort->dstPort)) {
74                     /* The VXLAN tunnel was already created. */
75                     return TRUE;
76                 }
77             }
78         }
79     }
80
81     return FALSE;
82 }
83
84 /*
85  *----------------------------------------------------------------------------
86  * This function allocates and initializes the OVS_VXLAN_VPORT. The function
87  * also creates a WFP tunnel filter for the necessary destination port. The
88  * tunnel filter create request is passed to the tunnel filter threads that
89  * will complete the request at a later time when IRQL is lowered to
90  * PASSIVE_LEVEL.
91  *
92  * udpDestPort: the vxlan is set as payload to a udp frame. If the destination
93  * port of an udp frame is udpDestPort, we understand it to be vxlan.
94  *----------------------------------------------------------------------------
95  */
96 NTSTATUS
97 OvsInitVxlanTunnel(PIRP irp,
98                    POVS_VPORT_ENTRY vport,
99                    UINT16 udpDestPort,
100                    PFNTunnelVportPendingOp callback,
101                    PVOID tunnelContext)
102 {
103     NTSTATUS status = STATUS_SUCCESS;
104     POVS_VXLAN_VPORT vxlanPort = NULL;
105
106     vxlanPort = OvsAllocateMemoryWithTag(sizeof (*vxlanPort),
107                                          OVS_VXLAN_POOL_TAG);
108     if (vxlanPort == NULL) {
109         return STATUS_INSUFFICIENT_RESOURCES;
110     }
111
112     RtlZeroMemory(vxlanPort, sizeof(*vxlanPort));
113     vxlanPort->dstPort = udpDestPort;
114     vport->priv = (PVOID)vxlanPort;
115
116     if (!OvsIsTunnelFilterCreated(gOvsSwitchContext, udpDestPort)) {
117         status = OvsTunnelFilterCreate(irp,
118                                        udpDestPort,
119                                        &vxlanPort->filterID,
120                                        callback,
121                                        tunnelContext);
122     } else {
123         status = STATUS_OBJECT_NAME_EXISTS;
124     }
125
126     return status;
127 }
128
129 /*
130  *----------------------------------------------------------------------------
131  * This function releases the OVS_VXLAN_VPORT. The function also deletes the
132  * WFP tunnel filter previously created. The tunnel filter delete request is
133  * passed to the tunnel filter threads that will complete the request at a
134  * later time when IRQL is lowered to PASSIVE_LEVEL.
135  *----------------------------------------------------------------------------
136  */
137 NTSTATUS
138 OvsCleanupVxlanTunnel(PIRP irp,
139                       POVS_VPORT_ENTRY vport,
140                       PFNTunnelVportPendingOp callback,
141                       PVOID tunnelContext)
142 {
143     NTSTATUS status = STATUS_SUCCESS;
144     POVS_VXLAN_VPORT vxlanPort = NULL;
145
146     if (vport->ovsType != OVS_VPORT_TYPE_VXLAN ||
147         vport->priv == NULL) {
148         return STATUS_SUCCESS;
149     }
150
151     vxlanPort = (POVS_VXLAN_VPORT)vport->priv;
152
153     if (vxlanPort->filterID != 0) {
154         status = OvsTunnelFilterDelete(irp,
155                                        vxlanPort->filterID,
156                                        callback,
157                                        tunnelContext);
158     } else {
159         OvsFreeMemoryWithTag(vport->priv, OVS_VXLAN_POOL_TAG);
160         vport->priv = NULL;
161     }
162
163     return status;
164 }
165
166
167 /*
168  *----------------------------------------------------------------------------
169  * OvsDoEncapVxlan
170  *     Encapsulates the packet.
171  *----------------------------------------------------------------------------
172  */
173 static __inline NDIS_STATUS
174 OvsDoEncapVxlan(POVS_VPORT_ENTRY vport,
175                 PNET_BUFFER_LIST curNbl,
176                 OvsIPv4TunnelKey *tunKey,
177                 POVS_FWD_INFO fwdInfo,
178                 POVS_PACKET_HDR_INFO layers,
179                 POVS_SWITCH_CONTEXT switchContext,
180                 PNET_BUFFER_LIST *newNbl)
181 {
182     NDIS_STATUS status;
183     PNET_BUFFER curNb;
184     PMDL curMdl;
185     PUINT8 bufferStart;
186     EthHdr *ethHdr;
187     IPHdr *ipHdr;
188     UDPHdr *udpHdr;
189     VXLANHdr *vxlanHdr;
190     POVS_VXLAN_VPORT vportVxlan;
191     UINT32 headRoom = OvsGetVxlanTunHdrSize();
192     UINT32 packetLength;
193
194     /*
195      * XXX: the assumption currently is that the NBL is owned by OVS, and
196      * headroom has already been allocated as part of allocating the NBL and
197      * MDL.
198      */
199     curNb = NET_BUFFER_LIST_FIRST_NB(curNbl);
200     packetLength = NET_BUFFER_DATA_LENGTH(curNb);
201     if (layers->isTcp) {
202         NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO tsoInfo;
203
204         tsoInfo.Value = NET_BUFFER_LIST_INFO(curNbl,
205                 TcpLargeSendNetBufferListInfo);
206         OVS_LOG_TRACE("MSS %u packet len %u", tsoInfo.LsoV1Transmit.MSS, packetLength);
207         if (tsoInfo.LsoV1Transmit.MSS) {
208             OVS_LOG_TRACE("l4Offset %d", layers->l4Offset);
209             *newNbl = OvsTcpSegmentNBL(switchContext, curNbl, layers,
210                         tsoInfo.LsoV1Transmit.MSS, headRoom);
211             if (*newNbl == NULL) {
212                 OVS_LOG_ERROR("Unable to segment NBL");
213                 return NDIS_STATUS_FAILURE;
214             }
215         }
216     }
217
218     vportVxlan = (POVS_VXLAN_VPORT) GetOvsVportPriv(vport);
219     ASSERT(vportVxlan);
220
221     /* If we didn't split the packet above, make a copy now */
222     if (*newNbl == NULL) {
223         *newNbl = OvsPartialCopyNBL(switchContext, curNbl, 0, headRoom,
224                                     FALSE /*NBL info*/);
225         if (*newNbl == NULL) {
226             OVS_LOG_ERROR("Unable to copy NBL");
227             return NDIS_STATUS_FAILURE;
228         }
229     }
230
231     curNbl = *newNbl;
232     for (curNb = NET_BUFFER_LIST_FIRST_NB(curNbl); curNb != NULL;
233             curNb = curNb->Next) {
234         status = NdisRetreatNetBufferDataStart(curNb, headRoom, 0, NULL);
235         if (status != NDIS_STATUS_SUCCESS) {
236             goto ret_error;
237         }
238
239         curMdl = NET_BUFFER_CURRENT_MDL(curNb);
240         bufferStart = (PUINT8)MmGetSystemAddressForMdlSafe(curMdl, LowPagePriority);
241         if (!bufferStart) {
242             status = NDIS_STATUS_RESOURCES;
243             goto ret_error;
244         }
245
246         bufferStart += NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
247         if (NET_BUFFER_NEXT_NB(curNb)) {
248             OVS_LOG_TRACE("nb length %u next %u", NET_BUFFER_DATA_LENGTH(curNb),
249                           NET_BUFFER_DATA_LENGTH(curNb->Next));
250         }
251
252         /* L2 header */
253         ethHdr = (EthHdr *)bufferStart;
254         ASSERT(((PCHAR)&fwdInfo->dstMacAddr + sizeof fwdInfo->dstMacAddr) ==
255                (PCHAR)&fwdInfo->srcMacAddr);
256         NdisMoveMemory(ethHdr->Destination, fwdInfo->dstMacAddr,
257                        sizeof ethHdr->Destination + sizeof ethHdr->Source);
258         ethHdr->Type = htons(ETH_TYPE_IPV4);
259
260         // XXX: question: there are fields in the OvsIPv4TunnelKey for ttl and such,
261         // should we use those values instead? or will they end up being
262         // uninitialized;
263         /* IP header */
264         ipHdr = (IPHdr *)((PCHAR)ethHdr + sizeof *ethHdr);
265
266         ipHdr->ihl = sizeof *ipHdr / 4;
267         ipHdr->version = IPPROTO_IPV4;
268         ipHdr->tos = tunKey->tos;
269         ipHdr->tot_len = htons(NET_BUFFER_DATA_LENGTH(curNb) - sizeof *ethHdr);
270         ipHdr->id = (uint16)atomic_add64(&vportVxlan->ipId,
271                                          NET_BUFFER_DATA_LENGTH(curNb));
272         ipHdr->frag_off = (tunKey->flags & OVS_TNL_F_DONT_FRAGMENT) ?
273                           IP_DF_NBO : 0;
274         ipHdr->ttl = tunKey->ttl ? tunKey->ttl : VXLAN_DEFAULT_TTL;
275         ipHdr->protocol = IPPROTO_UDP;
276         ASSERT(tunKey->dst == fwdInfo->dstIpAddr);
277         ASSERT(tunKey->src == fwdInfo->srcIpAddr || tunKey->src == 0);
278         ipHdr->saddr = fwdInfo->srcIpAddr;
279         ipHdr->daddr = fwdInfo->dstIpAddr;
280         ipHdr->check = 0;
281         ipHdr->check = IPChecksum((UINT8 *)ipHdr, sizeof *ipHdr, 0);
282
283         /* UDP header */
284         udpHdr = (UDPHdr *)((PCHAR)ipHdr + sizeof *ipHdr);
285         udpHdr->source = htons(tunKey->flow_hash | MAXINT16);
286         udpHdr->dest = htons(vportVxlan->dstPort);
287         udpHdr->len = htons(NET_BUFFER_DATA_LENGTH(curNb) - headRoom +
288                             sizeof *udpHdr + sizeof *vxlanHdr);
289         udpHdr->check = 0;
290
291         /* VXLAN header */
292         vxlanHdr = (VXLANHdr *)((PCHAR)udpHdr + sizeof *udpHdr);
293         vxlanHdr->flags1 = 0;
294         vxlanHdr->locallyReplicate = 0;
295         vxlanHdr->flags2 = 0;
296         vxlanHdr->reserved1 = 0;
297         if (tunKey->flags | OVS_TNL_F_KEY) {
298             vxlanHdr->vxlanID = VXLAN_TUNNELID_TO_VNI(tunKey->tunnelId);
299             vxlanHdr->instanceID = 1;
300         }
301         vxlanHdr->reserved2 = 0;
302     }
303     return STATUS_SUCCESS;
304
305 ret_error:
306     OvsCompleteNBL(switchContext, *newNbl, TRUE);
307     *newNbl = NULL;
308     return status;
309 }
310
311
312 /*
313  *----------------------------------------------------------------------------
314  * OvsEncapVxlan --
315  *     Encapsulates the packet if L2/L3 for destination resolves. Otherwise,
316  *     enqueues a callback that does encapsulatation after resolution.
317  *----------------------------------------------------------------------------
318  */
319 NDIS_STATUS
320 OvsEncapVxlan(POVS_VPORT_ENTRY vport,
321               PNET_BUFFER_LIST curNbl,
322               OvsIPv4TunnelKey *tunKey,
323               POVS_SWITCH_CONTEXT switchContext,
324               POVS_PACKET_HDR_INFO layers,
325               PNET_BUFFER_LIST *newNbl)
326 {
327     NTSTATUS status;
328     OVS_FWD_INFO fwdInfo;
329
330     status = OvsLookupIPFwdInfo(tunKey->dst, &fwdInfo);
331     if (status != STATUS_SUCCESS) {
332         OvsFwdIPHelperRequest(NULL, 0, tunKey, NULL, NULL, NULL);
333         // return NDIS_STATUS_PENDING;
334         /*
335          * XXX: Don't know if the completionList will make any sense when
336          * accessed in the callback. Make sure the caveats are known.
337          *
338          * XXX: This code will work once we are able to grab locks in the
339          * callback.
340          */
341         return NDIS_STATUS_FAILURE;
342     }
343
344     return OvsDoEncapVxlan(vport, curNbl, tunKey, &fwdInfo, layers,
345                            switchContext, newNbl);
346 }
347
348 /*
349  *----------------------------------------------------------------------------
350  * OvsCalculateUDPChecksum
351  *     Calculate UDP checksum
352  *----------------------------------------------------------------------------
353  */
354 static __inline NDIS_STATUS
355 OvsCalculateUDPChecksum(PNET_BUFFER_LIST curNbl,
356                         PNET_BUFFER curNb,
357                         IPHdr *ipHdr,
358                         UDPHdr *udpHdr,
359                         UINT32 packetLength)
360 {
361     NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO csumInfo;
362     UINT16 checkSum;
363
364     csumInfo.Value = NET_BUFFER_LIST_INFO(curNbl, TcpIpChecksumNetBufferListInfo);
365
366     /* Next check if UDP checksum has been calculated. */
367     if (!csumInfo.Receive.UdpChecksumSucceeded) {
368         UINT32 l4Payload;
369
370         checkSum = udpHdr->check;
371
372         l4Payload = packetLength - sizeof(EthHdr) - ipHdr->ihl * 4;
373         udpHdr->check = 0;
374         udpHdr->check =
375             IPPseudoChecksum((UINT32 *)&ipHdr->saddr,
376                              (UINT32 *)&ipHdr->daddr,
377                              IPPROTO_UDP, (UINT16)l4Payload);
378         udpHdr->check = CalculateChecksumNB(curNb, (UINT16)l4Payload,
379             sizeof(EthHdr) + ipHdr->ihl * 4);
380         if (checkSum != udpHdr->check) {
381             OVS_LOG_TRACE("UDP checksum incorrect.");
382             return NDIS_STATUS_INVALID_PACKET;
383         }
384     }
385
386     csumInfo.Receive.UdpChecksumSucceeded = 1;
387     NET_BUFFER_LIST_INFO(curNbl, TcpIpChecksumNetBufferListInfo) = csumInfo.Value;
388     return NDIS_STATUS_SUCCESS;
389 }
390
391 /*
392  *----------------------------------------------------------------------------
393  * OvsDecapVxlan
394  *     Decapsulates to tunnel header in 'curNbl' and puts into 'tunKey'.
395  *----------------------------------------------------------------------------
396  */
397 NDIS_STATUS
398 OvsDecapVxlan(POVS_SWITCH_CONTEXT switchContext,
399               PNET_BUFFER_LIST curNbl,
400               OvsIPv4TunnelKey *tunKey,
401               PNET_BUFFER_LIST *newNbl)
402 {
403     PNET_BUFFER curNb;
404     PMDL curMdl;
405     EthHdr *ethHdr;
406     IPHdr *ipHdr;
407     UDPHdr *udpHdr;
408     VXLANHdr *vxlanHdr;
409     UINT32 tunnelSize = 0, packetLength = 0;
410     PUINT8 bufferStart;
411     NDIS_STATUS status;
412
413     /* Check the the length of the UDP payload */
414     curNb = NET_BUFFER_LIST_FIRST_NB(curNbl);
415     packetLength = NET_BUFFER_DATA_LENGTH(curNb);
416     tunnelSize = OvsGetVxlanTunHdrSize();
417     if (packetLength <= tunnelSize) {
418         return NDIS_STATUS_INVALID_LENGTH;
419     }
420
421     /*
422      * Create a copy of the NBL so that we have all the headers in one MDL.
423      */
424     *newNbl = OvsPartialCopyNBL(switchContext, curNbl,
425                                 tunnelSize + OVS_DEFAULT_COPY_SIZE, 0,
426                                 TRUE /*copy NBL info */);
427
428     if (*newNbl == NULL) {
429         return NDIS_STATUS_RESOURCES;
430     }
431
432     /* XXX: Handle VLAN header. */
433     curNbl = *newNbl;
434     curNb = NET_BUFFER_LIST_FIRST_NB(curNbl);
435     curMdl = NET_BUFFER_CURRENT_MDL(curNb);
436     bufferStart = (PUINT8)MmGetSystemAddressForMdlSafe(curMdl, LowPagePriority) +
437                   NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
438     if (!bufferStart) {
439         status = NDIS_STATUS_RESOURCES;
440         goto dropNbl;
441     }
442
443     ethHdr = (EthHdr *)bufferStart;
444     /* XXX: Handle IP options. */
445     ipHdr = (IPHdr *)((PCHAR)ethHdr + sizeof *ethHdr);
446     tunKey->src = ipHdr->saddr;
447     tunKey->dst = ipHdr->daddr;
448     tunKey->tos = ipHdr->tos;
449     tunKey->ttl = ipHdr->ttl;
450     tunKey->pad = 0;
451     udpHdr = (UDPHdr *)((PCHAR)ipHdr + sizeof *ipHdr);
452
453     /* Validate if NIC has indicated checksum failure. */
454     status = OvsValidateUDPChecksum(curNbl, udpHdr->check == 0);
455     if (status != NDIS_STATUS_SUCCESS) {
456         goto dropNbl;
457     }
458
459     /* Calculate and verify UDP checksum if NIC didn't do it. */
460     if (udpHdr->check != 0) {
461         status = OvsCalculateUDPChecksum(curNbl, curNb, ipHdr, udpHdr, packetLength);
462         if (status != NDIS_STATUS_SUCCESS) {
463             goto dropNbl;
464         }
465     }
466
467     vxlanHdr = (VXLANHdr *)((PCHAR)udpHdr + sizeof *udpHdr);
468     if (vxlanHdr->instanceID) {
469         tunKey->flags = OVS_TNL_F_KEY;
470         tunKey->tunnelId = VXLAN_VNI_TO_TUNNELID(vxlanHdr->vxlanID);
471     } else {
472         tunKey->flags = 0;
473         tunKey->tunnelId = 0;
474     }
475
476     /* Clear out the receive flag for the inner packet. */
477     NET_BUFFER_LIST_INFO(curNbl, TcpIpChecksumNetBufferListInfo) = 0;
478     NdisAdvanceNetBufferDataStart(curNb, tunnelSize, FALSE, NULL);
479     return NDIS_STATUS_SUCCESS;
480
481 dropNbl:
482     OvsCompleteNBL(switchContext, *newNbl, TRUE);
483     *newNbl = NULL;
484     return status;
485 }
486
487
488 NDIS_STATUS
489 OvsSlowPathDecapVxlan(const PNET_BUFFER_LIST packet,
490                    OvsIPv4TunnelKey *tunnelKey)
491 {
492     NDIS_STATUS status = NDIS_STATUS_FAILURE;
493     UDPHdr udpStorage;
494     const UDPHdr *udp;
495     VXLANHdr *VxlanHeader;
496     VXLANHdr  VxlanHeaderBuffer;
497     struct IPHdr ip_storage;
498     const struct IPHdr *nh;
499     OVS_PACKET_HDR_INFO layers;
500
501     layers.value = 0;
502
503     do {
504         nh = OvsGetIp(packet, layers.l3Offset, &ip_storage);
505         if (nh) {
506             layers.l4Offset = layers.l3Offset + nh->ihl * 4;
507         } else {
508             break;
509         }
510
511         /* make sure it's a VXLAN packet */
512         udp = OvsGetUdp(packet, layers.l4Offset, &udpStorage);
513         if (udp) {
514             layers.l7Offset = layers.l4Offset + sizeof *udp;
515         } else {
516             break;
517         }
518
519         VxlanHeader = (VXLANHdr *)OvsGetPacketBytes(packet,
520                                                     sizeof(*VxlanHeader),
521                                                     layers.l7Offset,
522                                                     &VxlanHeaderBuffer);
523
524         if (VxlanHeader) {
525             tunnelKey->src = nh->saddr;
526             tunnelKey->dst = nh->daddr;
527             tunnelKey->ttl = nh->ttl;
528             tunnelKey->tos = nh->tos;
529             if (VxlanHeader->instanceID) {
530                 tunnelKey->flags = OVS_TNL_F_KEY;
531                 tunnelKey->tunnelId = VXLAN_VNI_TO_TUNNELID(VxlanHeader->vxlanID);
532             } else {
533                 tunnelKey->flags = 0;
534                 tunnelKey->tunnelId = 0;
535             }
536         } else {
537             break;
538         }
539         status = NDIS_STATUS_SUCCESS;
540
541     } while(FALSE);
542
543     return status;
544 }
545
546 #pragma warning( pop )