summaryrefslogtreecommitdiff
path: root/datapath-windows/ovsext/Stt.c
blob: dd7bf927996509951ccfcf49d713144a4757d5c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
/*
 * Copyright (c) 2015, 2016 VMware, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "precomp.h"

#include "Atomic.h"
#include "Debug.h"
#include "Flow.h"
#include "IpHelper.h"
#include "Jhash.h"
#include "NetProto.h"
#include "Offload.h"
#include "PacketIO.h"
#include "PacketParser.h"
#include "Stt.h"
#include "Switch.h"
#include "User.h"
#include "Util.h"
#include "Vport.h"

#ifdef OVS_DBG_MOD
#undef OVS_DBG_MOD
#endif
#define OVS_DBG_MOD OVS_DBG_STT


KSTART_ROUTINE OvsSttDefragCleaner;
static PLIST_ENTRY OvsSttPktFragHash;
static NDIS_SPIN_LOCK OvsSttSpinLock;
static OVS_STT_THREAD_CTX sttDefragThreadCtx;

static NDIS_STATUS
OvsDoEncapStt(POVS_VPORT_ENTRY vport, PNET_BUFFER_LIST curNbl,
              const OvsIPv4TunnelKey *tunKey,
              const POVS_FWD_INFO fwdInfo,
              POVS_PACKET_HDR_INFO layers,
              POVS_SWITCH_CONTEXT switchContext,
              PNET_BUFFER_LIST *newNbl);

/*
 * --------------------------------------------------------------------------
 * OvsInitSttTunnel --
 *    Initialize STT tunnel module.
 * --------------------------------------------------------------------------
 */
NTSTATUS
OvsInitSttTunnel(POVS_VPORT_ENTRY vport,
                 UINT16 tcpDestPort)
{
    POVS_STT_VPORT sttPort;

    sttPort = (POVS_STT_VPORT) OvsAllocateMemoryWithTag(sizeof(*sttPort),
                                                        OVS_STT_POOL_TAG);
    if (!sttPort) {
        OVS_LOG_ERROR("Insufficient memory, can't allocate STT_VPORT");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    RtlZeroMemory(sttPort, sizeof(*sttPort));
    sttPort->dstPort = tcpDestPort;
    vport->priv = (PVOID) sttPort;
    return STATUS_SUCCESS;
}

/*
 * --------------------------------------------------------------------------
 * OvsCleanupSttTunnel --
 *    Cleanup STT Tunnel module.
 * --------------------------------------------------------------------------
 */
void
OvsCleanupSttTunnel(POVS_VPORT_ENTRY vport)
{
    if (vport->ovsType != OVS_VPORT_TYPE_STT ||
        vport->priv == NULL) {
        return;
    }

    OvsFreeMemoryWithTag(vport->priv, OVS_STT_POOL_TAG);
    vport->priv = NULL;
}

/*
 * --------------------------------------------------------------------------
 * OvsEncapStt --
 *     Encapsulates a packet with an STT header.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsEncapStt(POVS_VPORT_ENTRY vport,
            PNET_BUFFER_LIST curNbl,
            OvsIPv4TunnelKey *tunKey,
            POVS_SWITCH_CONTEXT switchContext,
            POVS_PACKET_HDR_INFO layers,
            PNET_BUFFER_LIST *newNbl)
{
    OVS_FWD_INFO fwdInfo;
    NDIS_STATUS status;

    UNREFERENCED_PARAMETER(switchContext);
    status = OvsLookupIPFwdInfo(tunKey->dst, &fwdInfo);
    if (status != STATUS_SUCCESS) {
        OvsFwdIPHelperRequest(NULL, 0, tunKey, NULL, NULL, NULL);
        /*
         * XXX This case where the ARP table is not populated is
         * currently not handled
         */
        return NDIS_STATUS_FAILURE;
    }

    status = OvsDoEncapStt(vport, curNbl, tunKey, &fwdInfo, layers,
                           switchContext, newNbl);
    return status;
}

/*
 * --------------------------------------------------------------------------
 * OvsDoEncapStt --
 *    Internal utility function which actually does the STT encap.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsDoEncapStt(POVS_VPORT_ENTRY vport,
              PNET_BUFFER_LIST curNbl,
              const OvsIPv4TunnelKey *tunKey,
              const POVS_FWD_INFO fwdInfo,
              POVS_PACKET_HDR_INFO layers,
              POVS_SWITCH_CONTEXT switchContext,
              PNET_BUFFER_LIST *newNbl)
{
    NDIS_STATUS status = NDIS_STATUS_SUCCESS;
    PMDL curMdl = NULL;
    PNET_BUFFER curNb;
    PUINT8 buf = NULL;
    EthHdr *outerEthHdr;
    IPHdr *outerIpHdr;
    TCPHdr *outerTcpHdr;
    SttHdr *sttHdr;
    UINT32 innerFrameLen, ipTotalLen;
    POVS_STT_VPORT vportStt;
    UINT32 headRoom = OvsGetSttTunHdrSize();
    UINT32 tcpChksumLen;
    PUINT8 bufferStart;
    ULONG mss = 0;
    NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO lsoInfo;

    curNb = NET_BUFFER_LIST_FIRST_NB(curNbl);

    /* Verify if inner checksum is verified */
    BOOLEAN innerChecksumVerified = FALSE;
    BOOLEAN innerPartialChecksum = FALSE;

    if (layers->isTcp) {
        mss = OVSGetTcpMSS(curNbl);
    }

    vportStt = (POVS_STT_VPORT) GetOvsVportPriv(vport);
    ASSERT(vportStt);

    NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO csumInfo;
    csumInfo.Value = NET_BUFFER_LIST_INFO(curNbl,
                                          TcpIpChecksumNetBufferListInfo);
    *newNbl = OvsPartialCopyNBL(switchContext, curNbl, 0, headRoom,
                                FALSE /*copy NblInfo*/);
    if (*newNbl == NULL) {
        OVS_LOG_ERROR("Unable to copy NBL");
        return NDIS_STATUS_FAILURE;
    }

    curNbl = *newNbl;
    curNb = NET_BUFFER_LIST_FIRST_NB(curNbl);
    curMdl = NET_BUFFER_CURRENT_MDL(curNb);
    /* NB Chain should be split before */
    ASSERT(NET_BUFFER_NEXT_NB(curNb) == NULL);
    innerFrameLen = NET_BUFFER_DATA_LENGTH(curNb);

    bufferStart = (PUINT8)MmGetSystemAddressForMdlSafe(curMdl,
                                                       LowPagePriority);
    bufferStart += NET_BUFFER_CURRENT_MDL_OFFSET(curNb);

    if (layers->isIPv4) {
        IPHdr *ip = (IPHdr *)(bufferStart + layers->l3Offset);
        if (!ip->tot_len) {
            ip->tot_len = htons(innerFrameLen - sizeof(EthHdr));
        }
        if (!ip->check) {
            ip->check = IPChecksum((UINT8 *)ip, ip->ihl * 4, 0);
        }
    }

    if (layers->isTcp) {
        if (mss) {
            innerPartialChecksum = TRUE;
        } else {
            if (!csumInfo.Transmit.TcpChecksum) {
                innerChecksumVerified = TRUE;
            } else {
                innerPartialChecksum = TRUE;
            }
        }
    } else if (layers->isUdp) {
        if(!csumInfo.Transmit.UdpChecksum) {
            innerChecksumVerified = TRUE;
        } else {
            innerPartialChecksum = TRUE;
        }
    }

    status = NdisRetreatNetBufferDataStart(curNb, headRoom, 0, NULL);
    if (status != NDIS_STATUS_SUCCESS) {
        ASSERT(!"Unable to NdisRetreatNetBufferDataStart(headroom)");
        OVS_LOG_ERROR("Unable to NdisRetreatNetBufferDataStart(headroom)");
        goto ret_error;
    }

    /*
     * Make sure that the headroom for the tunnel header is continguous in
     * memory.
     */
    curMdl = NET_BUFFER_CURRENT_MDL(curNb);
    ASSERT((int) (MmGetMdlByteCount(curMdl) - NET_BUFFER_CURRENT_MDL_OFFSET(curNb))
                >= (int) headRoom);

    buf = (PUINT8) MmGetSystemAddressForMdlSafe(curMdl, LowPagePriority);
    if (!buf) {
        ASSERT(!"MmGetSystemAddressForMdlSafe failed");
        OVS_LOG_ERROR("MmGetSystemAddressForMdlSafe failed");
        status = NDIS_STATUS_RESOURCES;
        goto ret_error;
    }

    buf += NET_BUFFER_CURRENT_MDL_OFFSET(curNb);
    outerEthHdr = (EthHdr *)buf;
    outerIpHdr = (IPHdr *) (outerEthHdr + 1);
    outerTcpHdr = (TCPHdr *) (outerIpHdr + 1);
    sttHdr = (SttHdr *) (outerTcpHdr + 1);

    /* L2 header */
    ASSERT(((PCHAR)&fwdInfo->dstMacAddr + sizeof fwdInfo->dstMacAddr) ==
            (PCHAR)&fwdInfo->srcMacAddr);
    NdisMoveMemory(outerEthHdr->Destination, fwdInfo->dstMacAddr,
                    sizeof outerEthHdr->Destination + sizeof outerEthHdr->Source);
    outerEthHdr->Type = htons(ETH_TYPE_IPV4);

    /* L3 header */
    outerIpHdr->ihl = sizeof(IPHdr) >> 2;
    outerIpHdr->version = IPPROTO_IPV4;
    outerIpHdr->tos = tunKey->tos;

    ipTotalLen = sizeof(IPHdr) + sizeof(TCPHdr) + STT_HDR_LEN + innerFrameLen;
    outerIpHdr->tot_len = htons(ipTotalLen);
    ASSERT(ipTotalLen < 65536);

    outerIpHdr->id = (uint16) atomic_add64(&vportStt->ipId, innerFrameLen);
    outerIpHdr->frag_off = (tunKey->flags & OVS_TNL_F_DONT_FRAGMENT) ?
                           IP_DF_NBO : 0;
    outerIpHdr->ttl = tunKey->ttl? tunKey->ttl : 64;
    outerIpHdr->protocol = IPPROTO_TCP;
    outerIpHdr->check = 0;
    outerIpHdr->saddr = fwdInfo->srcIpAddr;
    outerIpHdr->daddr = tunKey->dst;

    /* L4 header */
    RtlZeroMemory(outerTcpHdr, sizeof *outerTcpHdr);
    outerTcpHdr->source = htons(tunKey->flow_hash | 32768);
    outerTcpHdr->dest = htons(vportStt->dstPort);
    outerTcpHdr->seq = htonl((STT_HDR_LEN + innerFrameLen) <<
                             STT_SEQ_LEN_SHIFT);
    outerTcpHdr->ack_seq = htonl(atomic_inc64(&vportStt->ackNo));
    outerTcpHdr->doff = sizeof(TCPHdr) >> 2;
    outerTcpHdr->psh = 1;
    outerTcpHdr->ack = 1;
    outerTcpHdr->window = (uint16) ~0;

    /* Calculate pseudo header chksum */
    tcpChksumLen = sizeof(TCPHdr) + STT_HDR_LEN + innerFrameLen;
    ASSERT(tcpChksumLen < 65535);
    outerTcpHdr->check = IPPseudoChecksum(&fwdInfo->srcIpAddr,(uint32 *) &tunKey->dst,
                                          IPPROTO_TCP, (uint16) tcpChksumLen);
    sttHdr->version = 0;

    /* Set STT Header */
    sttHdr->flags = 0;
    if (innerPartialChecksum) {
        sttHdr->flags |= STT_CSUM_PARTIAL;
        if (layers->isIPv4) {
            sttHdr->flags |= STT_PROTO_IPV4;
        }
        if (layers->isTcp) {
            sttHdr->flags |= STT_PROTO_TCP;
        }
        sttHdr->l4Offset = (UINT8) layers->l4Offset;
        sttHdr->mss = (UINT16) htons(mss);
    } else if (innerChecksumVerified) {
        sttHdr->flags = STT_CSUM_VERIFIED;
        sttHdr->l4Offset = 0;
        sttHdr->mss = 0;
    }

    sttHdr->reserved = 0;
    sttHdr->vlanTCI = 0;
    sttHdr->key = tunKey->tunnelId;
    /* Zero out stt padding */
    *(uint16 *)(sttHdr + 1) = 0;

    /* Offload IP and TCP checksum */
    ULONG tcpHeaderOffset = sizeof *outerEthHdr +
                        outerIpHdr->ihl * 4;
    csumInfo.Value = 0;
    csumInfo.Transmit.IpHeaderChecksum = 1;
    csumInfo.Transmit.TcpChecksum = 1;
    csumInfo.Transmit.IsIPv4 = 1;
    csumInfo.Transmit.TcpHeaderOffset = tcpHeaderOffset;
    NET_BUFFER_LIST_INFO(curNbl,
                         TcpIpChecksumNetBufferListInfo) = csumInfo.Value;

    UINT32 encapMss = OvsGetExternalMtu(switchContext) - sizeof(IPHdr) - sizeof(TCPHdr);
    if (ipTotalLen > encapMss) {
        lsoInfo.Value = 0;
        lsoInfo.LsoV2Transmit.TcpHeaderOffset = tcpHeaderOffset;
        lsoInfo.LsoV2Transmit.MSS = encapMss;
        lsoInfo.LsoV2Transmit.Type = NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE;
        lsoInfo.LsoV2Transmit.IPVersion = NDIS_TCP_LARGE_SEND_OFFLOAD_IPv4;
        NET_BUFFER_LIST_INFO(curNbl,
                             TcpLargeSendNetBufferListInfo) = lsoInfo.Value;
    }

    return STATUS_SUCCESS;

ret_error:
    OvsCompleteNBL(switchContext, *newNbl, TRUE);
    *newNbl = NULL;
    return status;
}

/*
 *----------------------------------------------------------------------------
 * OvsValidateTCPChecksum
 *     Validate TCP checksum
 *----------------------------------------------------------------------------
 */
static __inline NDIS_STATUS
OvsValidateTCPChecksum(PNET_BUFFER_LIST curNbl, PNET_BUFFER curNb)
{
    NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO csumInfo;
    csumInfo.Value = NET_BUFFER_LIST_INFO(curNbl,
                                          TcpIpChecksumNetBufferListInfo);

    /* Check if NIC has indicated TCP checksum failure */
    if (csumInfo.Receive.TcpChecksumFailed) {
        return NDIS_STATUS_INVALID_PACKET;
    }

    UINT16 checkSum;

    /* Check if TCP Checksum has been calculated by NIC */
    if (csumInfo.Receive.TcpChecksumSucceeded) {
        return NDIS_STATUS_SUCCESS;
    }

    EthHdr *eth = (EthHdr *)NdisGetDataBuffer(curNb, sizeof(EthHdr),
                                              NULL, 1, 0);

    if (eth->Type == ntohs(NDIS_ETH_TYPE_IPV4)) {
        IPHdr *ip = (IPHdr *)((PCHAR)eth + sizeof *eth);
        UINT32 l4Payload = ntohs(ip->tot_len) - ip->ihl * 4;
        TCPHdr *tcp = (TCPHdr *)((PCHAR)ip + ip->ihl * 4);
        checkSum = tcp->check;

        tcp->check = 0;
        tcp->check = IPPseudoChecksum(&ip->saddr, &ip->daddr,
                                      IPPROTO_TCP, (UINT16)l4Payload);
        tcp->check = CalculateChecksumNB(curNb, (UINT16)(l4Payload),
                                         sizeof(EthHdr) + ip->ihl * 4);
        if (checkSum != tcp->check) {
            return NDIS_STATUS_INVALID_PACKET;
        }
    } else {
        OVS_LOG_ERROR("IPv6 on STT is not supported");
        return NDIS_STATUS_INVALID_PACKET;
    }

    csumInfo.Receive.TcpChecksumSucceeded = 1;
    NET_BUFFER_LIST_INFO(curNbl,
                         TcpIpChecksumNetBufferListInfo) = csumInfo.Value;
    return NDIS_STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsInitSttDefragmentation
 *     Initialize the components used by the stt lso defragmentation
 *----------------------------------------------------------------------------
 */
NTSTATUS
OvsInitSttDefragmentation()
{
    NTSTATUS status;
    HANDLE threadHandle = NULL;

    /* Init the sync-lock */
    NdisAllocateSpinLock(&OvsSttSpinLock);

    /* Init the Hash Buffer */
    OvsSttPktFragHash = OvsAllocateMemoryWithTag(sizeof(LIST_ENTRY)
                                                 * STT_HASH_TABLE_SIZE,
                                                 OVS_STT_POOL_TAG);
    if (OvsSttPktFragHash == NULL) {
        NdisFreeSpinLock(&OvsSttSpinLock);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    for (int i = 0; i < STT_HASH_TABLE_SIZE; i++) {
        InitializeListHead(&OvsSttPktFragHash[i]);
    }

    /* Init Defrag Cleanup Thread */
    KeInitializeEvent(&sttDefragThreadCtx.event, NotificationEvent, FALSE);
    status = PsCreateSystemThread(&threadHandle, SYNCHRONIZE, NULL, NULL,
                                  NULL, OvsSttDefragCleaner,
                                  &sttDefragThreadCtx);

    if (status != STATUS_SUCCESS) {
        OvsCleanupSttDefragmentation();
        return status;
    }

    ObReferenceObjectByHandle(threadHandle, SYNCHRONIZE, NULL, KernelMode,
                              &sttDefragThreadCtx.threadObject, NULL);
    ZwClose(threadHandle);
    threadHandle = NULL;
    return STATUS_SUCCESS;
}

/*
 *----------------------------------------------------------------------------
 * OvsCleanupSttDefragmentation
 *     Cleanup memory and thread that were spawned for STT LSO defragmentation
 *----------------------------------------------------------------------------
 */
VOID
OvsCleanupSttDefragmentation(VOID)
{
    NdisAcquireSpinLock(&OvsSttSpinLock);
    sttDefragThreadCtx.exit = 1;
    KeSetEvent(&sttDefragThreadCtx.event, 0, FALSE);
    NdisReleaseSpinLock(&OvsSttSpinLock);

    KeWaitForSingleObject(sttDefragThreadCtx.threadObject, Executive,
                          KernelMode, FALSE, NULL);
    ObDereferenceObject(sttDefragThreadCtx.threadObject);

    if (OvsSttPktFragHash) {
        OvsFreeMemoryWithTag(OvsSttPktFragHash, OVS_STT_POOL_TAG);
        OvsSttPktFragHash = NULL;
    }

    NdisFreeSpinLock(&OvsSttSpinLock);
}

/*
 *----------------------------------------------------------------------------
 * OvsSttDefragCleaner
 *     Runs periodically and cleans up the buffer to remove expired segments
 *----------------------------------------------------------------------------
 */
VOID
OvsSttDefragCleaner(PVOID data)
{
    POVS_STT_THREAD_CTX context = (POVS_STT_THREAD_CTX)data;
    PLIST_ENTRY link, next;
    POVS_STT_PKT_ENTRY entry;
    BOOLEAN success = TRUE;

    while (success) {
        NdisAcquireSpinLock(&OvsSttSpinLock);
        if (context->exit) {
            NdisReleaseSpinLock(&OvsSttSpinLock);
            break;
        }

        /* Set the timeout for the thread and cleanup */
        UINT64 currentTime, threadSleepTimeout;
        NdisGetCurrentSystemTime((LARGE_INTEGER *)&currentTime);
        threadSleepTimeout = currentTime + STT_CLEANUP_INTERVAL;

        for (int i = 0; i < STT_HASH_TABLE_SIZE; i++) {
            LIST_FORALL_SAFE(&OvsSttPktFragHash[i], link, next) {
                entry = CONTAINING_RECORD(link, OVS_STT_PKT_ENTRY, link);
                if (entry->timeout < currentTime) {
                    RemoveEntryList(&entry->link);
                    OvsFreeMemoryWithTag(entry->packetBuf, OVS_STT_POOL_TAG);
                    OvsFreeMemoryWithTag(entry, OVS_STT_POOL_TAG);
                }
            }
        }

        NdisReleaseSpinLock(&OvsSttSpinLock);
        KeWaitForSingleObject(&context->event, Executive, KernelMode,
                              FALSE, (LARGE_INTEGER *)&threadSleepTimeout);
    }

    PsTerminateSystemThread(STATUS_SUCCESS);
}

static OVS_STT_PKT_KEY
OvsGeneratePacketKey(IPHdr *ipHdr, TCPHdr *tcpHdr)
{
    OVS_STT_PKT_KEY key;
    key.sAddr = ipHdr->saddr;
    key.dAddr = ipHdr->daddr;
    key.ackSeq = ntohl(tcpHdr->ack_seq);
    return key;
}

static UINT32
OvsSttGetPktHash(OVS_STT_PKT_KEY *pktKey)
{
    UINT32 arr[3];
    arr[0] = pktKey->ackSeq;
    arr[1] = pktKey->dAddr;
    arr[2] = pktKey->sAddr;
    return OvsJhashWords(arr, 3, OVS_HASH_BASIS);
}

static VOID *
OvsLookupPktFrag(OVS_STT_PKT_KEY *pktKey, UINT32 hash)
{
    PLIST_ENTRY link;
    POVS_STT_PKT_ENTRY entry;

    LIST_FORALL(&OvsSttPktFragHash[hash & STT_HASH_TABLE_MASK], link) {
        entry = CONTAINING_RECORD(link, OVS_STT_PKT_ENTRY, link);
        if (entry->ovsPktKey.ackSeq == pktKey->ackSeq &&
            entry->ovsPktKey.dAddr == pktKey->dAddr &&
            entry->ovsPktKey.sAddr == pktKey->sAddr) {
            return entry;
        }
    }
    return NULL;
}

/*
*
--------------------------------------------------------------------------
* OvsSttReassemble --
*     Reassemble an LSO packet from multiple STT-Fragments.
*
--------------------------------------------------------------------------
*/
PNET_BUFFER_LIST
OvsSttReassemble(POVS_SWITCH_CONTEXT switchContext,
                 PNET_BUFFER_LIST curNbl,
                 IPHdr *ipHdr,
                 TCPHdr *tcp,
                 SttHdr *newSttHdr,
                 UINT16 payloadLen)
{
    UINT32 seq = ntohl(tcp->seq);
    UINT32 innerPacketLen = (seq >> STT_SEQ_LEN_SHIFT) - STT_HDR_LEN;
    UINT32 segOffset = STT_SEGMENT_OFF(seq);
    UINT32 offset = segOffset == 0 ? 0 : segOffset - STT_HDR_LEN;
    UINT32 startOffset = 0;
    OVS_STT_PKT_ENTRY *pktFragEntry;
    PNET_BUFFER_LIST targetPNbl = NULL;
    BOOLEAN lastPacket = FALSE;
    PNET_BUFFER sourceNb;
    UINT32 fragmentLength = payloadLen;
    SttHdr stt;
    SttHdr *sttHdr = NULL;
    sourceNb = NET_BUFFER_LIST_FIRST_NB(curNbl);

    /* XXX optimize this lock */
    NdisAcquireSpinLock(&OvsSttSpinLock);

    /* If this is the first fragment, copy the STT header */
    if (segOffset == 0) {
        sttHdr = NdisGetDataBuffer(sourceNb, sizeof(SttHdr), &stt, 1, 0);
        if (sttHdr == NULL) {
            OVS_LOG_ERROR("Unable to retrieve STT header");
            return NULL;
        }
        fragmentLength = fragmentLength - STT_HDR_LEN;
        startOffset = startOffset + STT_HDR_LEN;
    }

    /* Lookup fragment */
    OVS_STT_PKT_KEY pktKey = OvsGeneratePacketKey(ipHdr, tcp);
    UINT32 hash = OvsSttGetPktHash(&pktKey);
    pktFragEntry = OvsLookupPktFrag(&pktKey, hash);

    if (pktFragEntry == NULL) {
        /* Create a new Packet Entry */
        POVS_STT_PKT_ENTRY entry;
        entry = OvsAllocateMemoryWithTag(sizeof(OVS_STT_PKT_ENTRY),
                                         OVS_STT_POOL_TAG);
        RtlZeroMemory(entry, sizeof (OVS_STT_PKT_ENTRY));

        /* Update Key, timestamp and recvdLen */
        NdisMoveMemory(&entry->ovsPktKey, &pktKey, sizeof (OVS_STT_PKT_KEY));

        entry->recvdLen = fragmentLength;

        UINT64 currentTime;
        NdisGetCurrentSystemTime((LARGE_INTEGER *) &currentTime);
        entry->timeout = currentTime + STT_ENTRY_TIMEOUT;

        if (segOffset == 0) {
            entry->sttHdr = *sttHdr;
        }

        /* Copy the data from Source to new buffer */
        entry->packetBuf = OvsAllocateMemoryWithTag(innerPacketLen,
                                                    OVS_STT_POOL_TAG);
        if (OvsGetPacketBytes(curNbl, fragmentLength, startOffset,
                              entry->packetBuf + offset) == NULL) {
            OVS_LOG_ERROR("Error when obtaining bytes from Packet");
            goto handle_error;
        }

        /* Insert the entry in the Static Buffer */
        InsertHeadList(&OvsSttPktFragHash[hash & STT_HASH_TABLE_MASK],
                       &entry->link);
    } else {
        /* Add to recieved length to identify if this is the last fragment */
        pktFragEntry->recvdLen += fragmentLength;
        lastPacket = (pktFragEntry->recvdLen == innerPacketLen);

        if (segOffset == 0) {
            pktFragEntry->sttHdr = *sttHdr;
        }

        /* Copy the fragment data from Source to existing buffer */
        if (OvsGetPacketBytes(curNbl, fragmentLength, startOffset,
                              pktFragEntry->packetBuf + offset) == NULL) {
            OVS_LOG_ERROR("Error when obtaining bytes from Packet");
            goto handle_error;
        }
    }

handle_error:
    if (lastPacket) {
        /* Retrieve the original STT header */
        NdisMoveMemory(newSttHdr, &pktFragEntry->sttHdr, sizeof (SttHdr));
        targetPNbl = OvsAllocateNBLFromBuffer(switchContext, pktFragEntry->packetBuf,
                                              innerPacketLen);

        /* Delete this entry and free up the memory/ */
        RemoveEntryList(&pktFragEntry->link);
        OvsFreeMemoryWithTag(pktFragEntry->packetBuf, OVS_STT_POOL_TAG);
        OvsFreeMemoryWithTag(pktFragEntry, OVS_STT_POOL_TAG);
    }

    NdisReleaseSpinLock(&OvsSttSpinLock);
    return lastPacket ? targetPNbl : NULL;
}

VOID
OvsDecapSetOffloads(PNET_BUFFER_LIST curNbl, SttHdr *sttHdr)
{
    if ((sttHdr->flags & STT_CSUM_VERIFIED)
        || !(sttHdr->flags & STT_CSUM_PARTIAL)) {
        return;
    }

    UINT8 protoType;
    NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO csumInfo;
    csumInfo.Value = 0;
    csumInfo.Transmit.IpHeaderChecksum = 0;
    csumInfo.Transmit.TcpHeaderOffset = sttHdr->l4Offset;
    protoType = sttHdr->flags & STT_PROTO_TYPES;
    switch (protoType) {
        case (STT_PROTO_IPV4 | STT_PROTO_TCP):
            /* TCP/IPv4 */
            csumInfo.Transmit.IsIPv4 = 1;
            csumInfo.Transmit.TcpChecksum = 1;
            break;
        case STT_PROTO_TCP:
            /* TCP/IPv6 */
            csumInfo.Transmit.IsIPv6 = 1;
            csumInfo.Transmit.TcpChecksum = 1;
            break;
        case STT_PROTO_IPV4:
            /* UDP/IPv4 */
            csumInfo.Transmit.IsIPv4 = 1;
            csumInfo.Transmit.UdpChecksum = 1;
            break;
        default:
            /* UDP/IPv6 */
            csumInfo.Transmit.IsIPv6 = 1;
            csumInfo.Transmit.UdpChecksum = 1;
    }
    NET_BUFFER_LIST_INFO(curNbl,
                         TcpIpChecksumNetBufferListInfo) = csumInfo.Value;

    if (sttHdr->mss) {
        NDIS_TCP_LARGE_SEND_OFFLOAD_NET_BUFFER_LIST_INFO lsoInfo;
        lsoInfo.Value = 0;
        lsoInfo.LsoV2Transmit.TcpHeaderOffset = sttHdr->l4Offset;
        lsoInfo.LsoV2Transmit.MSS = ETH_DEFAULT_MTU
                                    - sizeof(IPHdr)
                                    - sizeof(TCPHdr);
        lsoInfo.LsoV2Transmit.Type = NDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE;
        if (sttHdr->flags & STT_PROTO_IPV4) {
            lsoInfo.LsoV2Transmit.IPVersion = NDIS_TCP_LARGE_SEND_OFFLOAD_IPv4;
        } else {
            lsoInfo.LsoV2Transmit.IPVersion = NDIS_TCP_LARGE_SEND_OFFLOAD_IPv6;
        }
        NET_BUFFER_LIST_INFO(curNbl,
                             TcpLargeSendNetBufferListInfo) = lsoInfo.Value;
    }
}

/*
 * --------------------------------------------------------------------------
 * OvsDecapStt --
 *     Decapsulates an STT packet.
 * --------------------------------------------------------------------------
 */
NDIS_STATUS
OvsDecapStt(POVS_SWITCH_CONTEXT switchContext,
            PNET_BUFFER_LIST curNbl,
            OvsIPv4TunnelKey *tunKey,
            PNET_BUFFER_LIST *newNbl)
{
    NDIS_STATUS status = NDIS_STATUS_FAILURE;
    PNET_BUFFER curNb, newNb;
    IPHdr *ipHdr;
    char *ipBuf[sizeof(IPHdr)];
    SttHdr stt;
    SttHdr *sttHdr;
    char *sttBuf[STT_HDR_LEN];
    UINT32 advanceCnt, hdrLen;
    BOOLEAN isLsoPacket = FALSE;

    curNb = NET_BUFFER_LIST_FIRST_NB(curNbl);
    ASSERT(NET_BUFFER_NEXT_NB(curNb) == NULL);

    /* Validate the TCP Checksum */
    status = OvsValidateTCPChecksum(curNbl, curNb);
    if (status != NDIS_STATUS_SUCCESS) {
        return status;
    }

    /* Skip Eth header */
    hdrLen = sizeof(EthHdr);
    NdisAdvanceNetBufferDataStart(curNb, hdrLen, FALSE, NULL);
    advanceCnt = hdrLen;

    ipHdr = NdisGetDataBuffer(curNb, sizeof *ipHdr, (PVOID) &ipBuf,
                                                    1 /*no align*/, 0);
    ASSERT(ipHdr);

    TCPHdr *tcp = (TCPHdr *)((PCHAR)ipHdr + ipHdr->ihl * 4);

    /* Skip IP & TCP headers */
    hdrLen = sizeof(IPHdr) + sizeof(TCPHdr),
    NdisAdvanceNetBufferDataStart(curNb, hdrLen, FALSE, NULL);
    advanceCnt += hdrLen;

    UINT32 seq = ntohl(tcp->seq);
    UINT32 totalLen = (seq >> STT_SEQ_LEN_SHIFT);
    UINT16 payloadLen = (UINT16)ntohs(ipHdr->tot_len)
                        - (ipHdr->ihl * 4)
                        - (sizeof * tcp);

    /* Check if incoming packet requires reassembly */
    if (totalLen != payloadLen) {
        sttHdr = &stt;
        PNET_BUFFER_LIST pNbl = OvsSttReassemble(switchContext, curNbl,
                                                 ipHdr, tcp, sttHdr,
                                                 payloadLen);
        if (pNbl == NULL) {
            return NDIS_STATUS_SUCCESS;
        }

        *newNbl = pNbl;
        isLsoPacket = TRUE;
    } else {
        /* STT Header */
        sttHdr = NdisGetDataBuffer(curNb, sizeof *sttHdr,
                                   (PVOID) &sttBuf, 1 /*no align*/, 0);
        /* Skip stt header, DataOffset points to inner pkt now. */
        hdrLen = STT_HDR_LEN;
        NdisAdvanceNetBufferDataStart(curNb, hdrLen, FALSE, NULL);
        advanceCnt += hdrLen;

        *newNbl = OvsPartialCopyNBL(switchContext, curNbl, 0,
                                    0, FALSE /*copy NBL info*/);
    }

    if (*newNbl == NULL) {
        OVS_LOG_ERROR("Unable to allocate a new cloned NBL");
        return NDIS_STATUS_RESOURCES;
    }

    status = NdisRetreatNetBufferDataStart(curNb, advanceCnt, 0, NULL);
    if (status != NDIS_STATUS_SUCCESS) {
        OvsCompleteNBL(switchContext, *newNbl, TRUE);
        return NDIS_STATUS_FAILURE;
    }
    newNb = NET_BUFFER_LIST_FIRST_NB(*newNbl);

    ASSERT(sttHdr);

    /* Initialize the tunnel key */
    tunKey->dst = ipHdr->daddr;
    tunKey->src = ipHdr->saddr;
    tunKey->tunnelId = sttHdr->key;
    tunKey->flags = OVS_TNL_F_KEY;
    tunKey->tos = ipHdr->tos;
    tunKey->ttl = ipHdr->ttl;
    tunKey->pad = 0;

    /* Set Checksum and LSO offload flags */
    OvsDecapSetOffloads(*newNbl, sttHdr);

    return NDIS_STATUS_SUCCESS;
}