]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_lro.c
sctp: cleanup, no functional change
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_lro.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2007, Myricom Inc.
5  * Copyright (c) 2008, Intel Corporation.
6  * Copyright (c) 2012 The FreeBSD Foundation
7  * Copyright (c) 2016-2021 Mellanox Technologies.
8  * All rights reserved.
9  *
10  * Portions of this software were developed by Bjoern Zeeb
11  * under sponsorship from the FreeBSD Foundation.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/sockbuf.h>
49 #include <sys/sysctl.h>
50
51 #include <net/if.h>
52 #include <net/if_var.h>
53 #include <net/ethernet.h>
54 #include <net/bpf.h>
55 #include <net/vnet.h>
56
57 #include <netinet/in_systm.h>
58 #include <netinet/in.h>
59 #include <netinet/ip6.h>
60 #include <netinet/ip.h>
61 #include <netinet/ip_var.h>
62 #include <netinet/in_pcb.h>
63 #include <netinet6/in6_pcb.h>
64 #include <netinet/tcp.h>
65 #include <netinet/tcp_seq.h>
66 #include <netinet/tcp_lro.h>
67 #include <netinet/tcp_var.h>
68 #include <netinet/tcpip.h>
69 #include <netinet/tcp_hpts.h>
70 #include <netinet/tcp_log_buf.h>
71 #include <netinet/udp.h>
72 #include <netinet6/ip6_var.h>
73
74 #include <machine/in_cksum.h>
75
76 static MALLOC_DEFINE(M_LRO, "LRO", "LRO control structures");
77
78 #define TCP_LRO_TS_OPTION \
79     ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
80           (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)
81
82 static void     tcp_lro_rx_done(struct lro_ctrl *lc);
83 static int      tcp_lro_rx_common(struct lro_ctrl *lc, struct mbuf *m,
84                     uint32_t csum, bool use_hash);
85
86 #ifdef TCPHPTS
87 static bool     do_bpf_strip_and_compress(struct inpcb *, struct lro_ctrl *,
88                 struct lro_entry *, struct mbuf **, struct mbuf **, struct mbuf **, bool *, bool);
89
90 #endif
91
92 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, lro,  CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
93     "TCP LRO");
94
95 static long tcplro_stacks_wanting_mbufq;
96 counter_u64_t tcp_inp_lro_direct_queue;
97 counter_u64_t tcp_inp_lro_wokeup_queue;
98 counter_u64_t tcp_inp_lro_compressed;
99 counter_u64_t tcp_inp_lro_locks_taken;
100 counter_u64_t tcp_extra_mbuf;
101 counter_u64_t tcp_would_have_but;
102 counter_u64_t tcp_comp_total;
103 counter_u64_t tcp_uncomp_total;
104
105 static unsigned tcp_lro_entries = TCP_LRO_ENTRIES;
106 SYSCTL_UINT(_net_inet_tcp_lro, OID_AUTO, entries,
107     CTLFLAG_RDTUN | CTLFLAG_MPSAFE, &tcp_lro_entries, 0,
108     "default number of LRO entries");
109
110 static uint32_t tcp_lro_cpu_set_thresh = TCP_LRO_CPU_DECLARATION_THRESH;
111 SYSCTL_UINT(_net_inet_tcp_lro, OID_AUTO, lro_cpu_threshold,
112     CTLFLAG_RDTUN | CTLFLAG_MPSAFE, &tcp_lro_cpu_set_thresh, 0,
113     "Number of interrupts in a row on the same CPU that will make us declare an 'affinity' cpu?");
114
115 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, fullqueue, CTLFLAG_RD,
116     &tcp_inp_lro_direct_queue, "Number of lro's fully queued to transport");
117 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, wokeup, CTLFLAG_RD,
118     &tcp_inp_lro_wokeup_queue, "Number of lro's where we woke up transport via hpts");
119 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, compressed, CTLFLAG_RD,
120     &tcp_inp_lro_compressed, "Number of lro's compressed and sent to transport");
121 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, lockcnt, CTLFLAG_RD,
122     &tcp_inp_lro_locks_taken, "Number of lro's inp_wlocks taken");
123 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, extra_mbuf, CTLFLAG_RD,
124     &tcp_extra_mbuf, "Number of times we had an extra compressed ack dropped into the tp");
125 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, would_have_but, CTLFLAG_RD,
126     &tcp_would_have_but, "Number of times we would have had an extra compressed, but mget failed");
127 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, with_m_ackcmp, CTLFLAG_RD,
128     &tcp_comp_total, "Number of mbufs queued with M_ACKCMP flags set");
129 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, without_m_ackcmp, CTLFLAG_RD,
130     &tcp_uncomp_total, "Number of mbufs queued without M_ACKCMP");
131
132 void
133 tcp_lro_reg_mbufq(void)
134 {
135         atomic_fetchadd_long(&tcplro_stacks_wanting_mbufq, 1);
136 }
137
138 void
139 tcp_lro_dereg_mbufq(void)
140 {
141         atomic_fetchadd_long(&tcplro_stacks_wanting_mbufq, -1);
142 }
143
144 static __inline void
145 tcp_lro_active_insert(struct lro_ctrl *lc, struct lro_head *bucket,
146     struct lro_entry *le)
147 {
148
149         LIST_INSERT_HEAD(&lc->lro_active, le, next);
150         LIST_INSERT_HEAD(bucket, le, hash_next);
151 }
152
153 static __inline void
154 tcp_lro_active_remove(struct lro_entry *le)
155 {
156
157         LIST_REMOVE(le, next);          /* active list */
158         LIST_REMOVE(le, hash_next);     /* hash bucket */
159 }
160
161 int
162 tcp_lro_init(struct lro_ctrl *lc)
163 {
164         return (tcp_lro_init_args(lc, NULL, tcp_lro_entries, 0));
165 }
166
167 int
168 tcp_lro_init_args(struct lro_ctrl *lc, struct ifnet *ifp,
169     unsigned lro_entries, unsigned lro_mbufs)
170 {
171         struct lro_entry *le;
172         size_t size;
173         unsigned i, elements;
174
175         lc->lro_bad_csum = 0;
176         lc->lro_queued = 0;
177         lc->lro_flushed = 0;
178         lc->lro_mbuf_count = 0;
179         lc->lro_mbuf_max = lro_mbufs;
180         lc->lro_cnt = lro_entries;
181         lc->lro_ackcnt_lim = TCP_LRO_ACKCNT_MAX;
182         lc->lro_length_lim = TCP_LRO_LENGTH_MAX;
183         lc->ifp = ifp;
184         LIST_INIT(&lc->lro_free);
185         LIST_INIT(&lc->lro_active);
186
187         /* create hash table to accelerate entry lookup */
188         if (lro_entries > lro_mbufs)
189                 elements = lro_entries;
190         else
191                 elements = lro_mbufs;
192         lc->lro_hash = phashinit_flags(elements, M_LRO, &lc->lro_hashsz,
193             HASH_NOWAIT);
194         if (lc->lro_hash == NULL) {
195                 memset(lc, 0, sizeof(*lc));
196                 return (ENOMEM);
197         }
198
199         /* compute size to allocate */
200         size = (lro_mbufs * sizeof(struct lro_mbuf_sort)) +
201             (lro_entries * sizeof(*le));
202         lc->lro_mbuf_data = (struct lro_mbuf_sort *)
203             malloc(size, M_LRO, M_NOWAIT | M_ZERO);
204
205         /* check for out of memory */
206         if (lc->lro_mbuf_data == NULL) {
207                 free(lc->lro_hash, M_LRO);
208                 memset(lc, 0, sizeof(*lc));
209                 return (ENOMEM);
210         }
211         /* compute offset for LRO entries */
212         le = (struct lro_entry *)
213             (lc->lro_mbuf_data + lro_mbufs);
214
215         /* setup linked list */
216         for (i = 0; i != lro_entries; i++)
217                 LIST_INSERT_HEAD(&lc->lro_free, le + i, next);
218
219         return (0);
220 }
221
222 struct vxlan_header {
223         uint32_t        vxlh_flags;
224         uint32_t        vxlh_vni;
225 };
226
227 static inline void *
228 tcp_lro_low_level_parser(void *ptr, struct lro_parser *parser, bool update_data, bool is_vxlan)
229 {
230         const struct ether_vlan_header *eh;
231         void *old;
232         uint16_t eth_type;
233
234         if (update_data)
235                 memset(parser, 0, sizeof(*parser));
236
237         old = ptr;
238
239         if (is_vxlan) {
240                 const struct vxlan_header *vxh;
241                 vxh = ptr;
242                 ptr = (uint8_t *)ptr + sizeof(*vxh);
243                 if (update_data) {
244                         parser->data.vxlan_vni =
245                             vxh->vxlh_vni & htonl(0xffffff00);
246                 }
247         }
248
249         eh = ptr;
250         if (__predict_false(eh->evl_encap_proto == htons(ETHERTYPE_VLAN))) {
251                 eth_type = eh->evl_proto;
252                 if (update_data) {
253                         /* strip priority and keep VLAN ID only */
254                         parser->data.vlan_id = eh->evl_tag & htons(EVL_VLID_MASK);
255                 }
256                 /* advance to next header */
257                 ptr = (uint8_t *)ptr + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
258         } else {
259                 eth_type = eh->evl_encap_proto;
260                 /* advance to next header */
261                 ptr = (uint8_t *)ptr + ETHER_HDR_LEN;
262         }
263
264         switch (eth_type) {
265 #ifdef INET
266         case htons(ETHERTYPE_IP):
267                 parser->ip4 = ptr;
268                 /* Ensure there are no IPv4 options. */
269                 if ((parser->ip4->ip_hl << 2) != sizeof (*parser->ip4))
270                         break;
271                 /* .. and the packet is not fragmented. */
272                 if (parser->ip4->ip_off & htons(IP_MF|IP_OFFMASK))
273                         break;
274                 ptr = (uint8_t *)ptr + (parser->ip4->ip_hl << 2);
275                 if (update_data) {
276                         parser->data.s_addr.v4 = parser->ip4->ip_src;
277                         parser->data.d_addr.v4 = parser->ip4->ip_dst;
278                 }
279                 switch (parser->ip4->ip_p) {
280                 case IPPROTO_UDP:
281                         parser->udp = ptr;
282                         if (update_data) {
283                                 parser->data.lro_type = LRO_TYPE_IPV4_UDP;
284                                 parser->data.s_port = parser->udp->uh_sport;
285                                 parser->data.d_port = parser->udp->uh_dport;
286                         } else {
287                                 MPASS(parser->data.lro_type == LRO_TYPE_IPV4_UDP);
288                         }
289                         ptr = ((uint8_t *)ptr + sizeof(*parser->udp));
290                         parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
291                         return (ptr);
292                 case IPPROTO_TCP:
293                         parser->tcp = ptr;
294                         if (update_data) {
295                                 parser->data.lro_type = LRO_TYPE_IPV4_TCP;
296                                 parser->data.s_port = parser->tcp->th_sport;
297                                 parser->data.d_port = parser->tcp->th_dport;
298                         } else {
299                                 MPASS(parser->data.lro_type == LRO_TYPE_IPV4_TCP);
300                         }
301                         ptr = (uint8_t *)ptr + (parser->tcp->th_off << 2);
302                         parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
303                         return (ptr);
304                 default:
305                         break;
306                 }
307                 break;
308 #endif
309 #ifdef INET6
310         case htons(ETHERTYPE_IPV6):
311                 parser->ip6 = ptr;
312                 ptr = (uint8_t *)ptr + sizeof(*parser->ip6);
313                 if (update_data) {
314                         parser->data.s_addr.v6 = parser->ip6->ip6_src;
315                         parser->data.d_addr.v6 = parser->ip6->ip6_dst;
316                 }
317                 switch (parser->ip6->ip6_nxt) {
318                 case IPPROTO_UDP:
319                         parser->udp = ptr;
320                         if (update_data) {
321                                 parser->data.lro_type = LRO_TYPE_IPV6_UDP;
322                                 parser->data.s_port = parser->udp->uh_sport;
323                                 parser->data.d_port = parser->udp->uh_dport;
324                         } else {
325                                 MPASS(parser->data.lro_type == LRO_TYPE_IPV6_UDP);
326                         }
327                         ptr = (uint8_t *)ptr + sizeof(*parser->udp);
328                         parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
329                         return (ptr);
330                 case IPPROTO_TCP:
331                         parser->tcp = ptr;
332                         if (update_data) {
333                                 parser->data.lro_type = LRO_TYPE_IPV6_TCP;
334                                 parser->data.s_port = parser->tcp->th_sport;
335                                 parser->data.d_port = parser->tcp->th_dport;
336                         } else {
337                                 MPASS(parser->data.lro_type == LRO_TYPE_IPV6_TCP);
338                         }
339                         ptr = (uint8_t *)ptr + (parser->tcp->th_off << 2);
340                         parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
341                         return (ptr);
342                 default:
343                         break;
344                 }
345                 break;
346 #endif
347         default:
348                 break;
349         }
350         /* Invalid packet - cannot parse */
351         return (NULL);
352 }
353
354 static const int vxlan_csum = CSUM_INNER_L3_CALC | CSUM_INNER_L3_VALID |
355     CSUM_INNER_L4_CALC | CSUM_INNER_L4_VALID;
356
357 static inline struct lro_parser *
358 tcp_lro_parser(struct mbuf *m, struct lro_parser *po, struct lro_parser *pi, bool update_data)
359 {
360         void *data_ptr;
361
362         /* Try to parse outer headers first. */
363         data_ptr = tcp_lro_low_level_parser(m->m_data, po, update_data, false);
364         if (data_ptr == NULL || po->total_hdr_len > m->m_len)
365                 return (NULL);
366
367         if (update_data) {
368                 /* Store VLAN ID, if any. */
369                 if (__predict_false(m->m_flags & M_VLANTAG)) {
370                         po->data.vlan_id =
371                             htons(m->m_pkthdr.ether_vtag) & htons(EVL_VLID_MASK);
372                 }
373                 /* Store decrypted flag, if any. */
374                 if (__predict_false((m->m_pkthdr.csum_flags &
375                     CSUM_TLS_MASK) == CSUM_TLS_DECRYPTED))
376                         po->data.lro_flags |= LRO_FLAG_DECRYPTED;
377         }
378
379         switch (po->data.lro_type) {
380         case LRO_TYPE_IPV4_UDP:
381         case LRO_TYPE_IPV6_UDP:
382                 /* Check for VXLAN headers. */
383                 if ((m->m_pkthdr.csum_flags & vxlan_csum) != vxlan_csum)
384                         break;
385
386                 /* Try to parse inner headers. */
387                 data_ptr = tcp_lro_low_level_parser(data_ptr, pi, update_data, true);
388                 if (data_ptr == NULL || pi->total_hdr_len > m->m_len)
389                         break;
390
391                 /* Verify supported header types. */
392                 switch (pi->data.lro_type) {
393                 case LRO_TYPE_IPV4_TCP:
394                 case LRO_TYPE_IPV6_TCP:
395                         return (pi);
396                 default:
397                         break;
398                 }
399                 break;
400         case LRO_TYPE_IPV4_TCP:
401         case LRO_TYPE_IPV6_TCP:
402                 if (update_data)
403                         memset(pi, 0, sizeof(*pi));
404                 return (po);
405         default:
406                 break;
407         }
408         return (NULL);
409 }
410
411 static inline int
412 tcp_lro_trim_mbuf_chain(struct mbuf *m, const struct lro_parser *po)
413 {
414         int len;
415
416         switch (po->data.lro_type) {
417 #ifdef INET
418         case LRO_TYPE_IPV4_TCP:
419                 len = ((uint8_t *)po->ip4 - (uint8_t *)m->m_data) +
420                     ntohs(po->ip4->ip_len);
421                 break;
422 #endif
423 #ifdef INET6
424         case LRO_TYPE_IPV6_TCP:
425                 len = ((uint8_t *)po->ip6 - (uint8_t *)m->m_data) +
426                     ntohs(po->ip6->ip6_plen) + sizeof(*po->ip6);
427                 break;
428 #endif
429         default:
430                 return (TCP_LRO_CANNOT);
431         }
432
433         /*
434          * If the frame is padded beyond the end of the IP packet,
435          * then trim the extra bytes off:
436          */
437         if (__predict_true(m->m_pkthdr.len == len)) {
438                 return (0);
439         } else if (m->m_pkthdr.len > len) {
440                 m_adj(m, len - m->m_pkthdr.len);
441                 return (0);
442         }
443         return (TCP_LRO_CANNOT);
444 }
445
446 static struct tcphdr *
447 tcp_lro_get_th(struct mbuf *m)
448 {
449         return ((struct tcphdr *)((uint8_t *)m->m_data + m->m_pkthdr.lro_tcp_h_off));
450 }
451
452 static void
453 lro_free_mbuf_chain(struct mbuf *m)
454 {
455         struct mbuf *save;
456
457         while (m) {
458                 save = m->m_nextpkt;
459                 m->m_nextpkt = NULL;
460                 m_freem(m);
461                 m = save;
462         }
463 }
464
465 void
466 tcp_lro_free(struct lro_ctrl *lc)
467 {
468         struct lro_entry *le;
469         unsigned x;
470
471         /* reset LRO free list */
472         LIST_INIT(&lc->lro_free);
473
474         /* free active mbufs, if any */
475         while ((le = LIST_FIRST(&lc->lro_active)) != NULL) {
476                 tcp_lro_active_remove(le);
477                 lro_free_mbuf_chain(le->m_head);
478         }
479
480         /* free hash table */
481         free(lc->lro_hash, M_LRO);
482         lc->lro_hash = NULL;
483         lc->lro_hashsz = 0;
484
485         /* free mbuf array, if any */
486         for (x = 0; x != lc->lro_mbuf_count; x++)
487                 m_freem(lc->lro_mbuf_data[x].mb);
488         lc->lro_mbuf_count = 0;
489
490         /* free allocated memory, if any */
491         free(lc->lro_mbuf_data, M_LRO);
492         lc->lro_mbuf_data = NULL;
493 }
494
495 static uint16_t
496 tcp_lro_rx_csum_tcphdr(const struct tcphdr *th)
497 {
498         const uint16_t *ptr;
499         uint32_t csum;
500         uint16_t len;
501
502         csum = -th->th_sum;     /* exclude checksum field */
503         len = th->th_off;
504         ptr = (const uint16_t *)th;
505         while (len--) {
506                 csum += *ptr;
507                 ptr++;
508                 csum += *ptr;
509                 ptr++;
510         }
511         while (csum > 0xffff)
512                 csum = (csum >> 16) + (csum & 0xffff);
513
514         return (csum);
515 }
516
517 static uint16_t
518 tcp_lro_rx_csum_data(const struct lro_parser *pa, uint16_t tcp_csum)
519 {
520         uint32_t c;
521         uint16_t cs;
522
523         c = tcp_csum;
524
525         switch (pa->data.lro_type) {
526 #ifdef INET6
527         case LRO_TYPE_IPV6_TCP:
528                 /* Compute full pseudo IPv6 header checksum. */
529                 cs = in6_cksum_pseudo(pa->ip6, ntohs(pa->ip6->ip6_plen), pa->ip6->ip6_nxt, 0);
530                 break;
531 #endif
532 #ifdef INET
533         case LRO_TYPE_IPV4_TCP:
534                 /* Compute full pseudo IPv4 header checsum. */
535                 cs = in_addword(ntohs(pa->ip4->ip_len) - sizeof(*pa->ip4), IPPROTO_TCP);
536                 cs = in_pseudo(pa->ip4->ip_src.s_addr, pa->ip4->ip_dst.s_addr, htons(cs));
537                 break;
538 #endif
539         default:
540                 cs = 0;         /* Keep compiler happy. */
541                 break;
542         }
543
544         /* Complement checksum. */
545         cs = ~cs;
546         c += cs;
547
548         /* Remove TCP header checksum. */
549         cs = ~tcp_lro_rx_csum_tcphdr(pa->tcp);
550         c += cs;
551
552         /* Compute checksum remainder. */
553         while (c > 0xffff)
554                 c = (c >> 16) + (c & 0xffff);
555
556         return (c);
557 }
558
559 static void
560 tcp_lro_rx_done(struct lro_ctrl *lc)
561 {
562         struct lro_entry *le;
563
564         while ((le = LIST_FIRST(&lc->lro_active)) != NULL) {
565                 tcp_lro_active_remove(le);
566                 tcp_lro_flush(lc, le);
567         }
568 }
569
570 void
571 tcp_lro_flush_inactive(struct lro_ctrl *lc, const struct timeval *timeout)
572 {
573         struct lro_entry *le, *le_tmp;
574         uint64_t now, tov;
575         struct bintime bt;
576
577         NET_EPOCH_ASSERT();
578         if (LIST_EMPTY(&lc->lro_active))
579                 return;
580
581         /* get timeout time and current time in ns */
582         binuptime(&bt);
583         now = bintime2ns(&bt);
584         tov = ((timeout->tv_sec * 1000000000) + (timeout->tv_usec * 1000));
585         LIST_FOREACH_SAFE(le, &lc->lro_active, next, le_tmp) {
586                 if (now >= (bintime2ns(&le->alloc_time) + tov)) {
587                         tcp_lro_active_remove(le);
588                         tcp_lro_flush(lc, le);
589                 }
590         }
591 }
592
593 #ifdef INET
594 static int
595 tcp_lro_rx_ipv4(struct lro_ctrl *lc, struct mbuf *m, struct ip *ip4)
596 {
597         uint16_t csum;
598
599         /* Legacy IP has a header checksum that needs to be correct. */
600         if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
601                 if (__predict_false((m->m_pkthdr.csum_flags & CSUM_IP_VALID) == 0)) {
602                         lc->lro_bad_csum++;
603                         return (TCP_LRO_CANNOT);
604                 }
605         } else {
606                 csum = in_cksum_hdr(ip4);
607                 if (__predict_false(csum != 0)) {
608                         lc->lro_bad_csum++;
609                         return (TCP_LRO_CANNOT);
610                 }
611         }
612         return (0);
613 }
614 #endif
615
616 #ifdef TCPHPTS
617 static void
618 tcp_lro_log(struct tcpcb *tp, const struct lro_ctrl *lc,
619     const struct lro_entry *le, const struct mbuf *m,
620     int frm, int32_t tcp_data_len, uint32_t th_seq,
621     uint32_t th_ack, uint16_t th_win)
622 {
623         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
624                 union tcp_log_stackspecific log;
625                 struct timeval tv, btv;
626                 uint32_t cts;
627
628                 cts = tcp_get_usecs(&tv);
629                 memset(&log, 0, sizeof(union tcp_log_stackspecific));
630                 log.u_bbr.flex8 = frm;
631                 log.u_bbr.flex1 = tcp_data_len;
632                 if (m)
633                         log.u_bbr.flex2 = m->m_pkthdr.len;
634                 else
635                         log.u_bbr.flex2 = 0;
636                 log.u_bbr.flex3 = le->m_head->m_pkthdr.lro_nsegs;
637                 log.u_bbr.flex4 = le->m_head->m_pkthdr.lro_tcp_d_len;
638                 if (le->m_head) {
639                         log.u_bbr.flex5 = le->m_head->m_pkthdr.len;
640                         log.u_bbr.delRate = le->m_head->m_flags;
641                         log.u_bbr.rttProp = le->m_head->m_pkthdr.rcv_tstmp;
642                 }
643                 log.u_bbr.inflight = th_seq;
644                 log.u_bbr.delivered = th_ack;
645                 log.u_bbr.timeStamp = cts;
646                 log.u_bbr.epoch = le->next_seq;
647                 log.u_bbr.lt_epoch = le->ack_seq;
648                 log.u_bbr.pacing_gain = th_win;
649                 log.u_bbr.cwnd_gain = le->window;
650                 log.u_bbr.lost = curcpu;
651                 log.u_bbr.cur_del_rate = (uintptr_t)m;
652                 log.u_bbr.bw_inuse = (uintptr_t)le->m_head;
653                 bintime2timeval(&lc->lro_last_queue_time, &btv);
654                 log.u_bbr.flex6 = tcp_tv_to_usectick(&btv);
655                 log.u_bbr.flex7 = le->compressed;
656                 log.u_bbr.pacing_gain = le->uncompressed;
657                 if (in_epoch(net_epoch_preempt))
658                         log.u_bbr.inhpts = 1;
659                 else
660                         log.u_bbr.inhpts = 0;
661                 TCP_LOG_EVENTP(tp, NULL,
662                                &tp->t_inpcb->inp_socket->so_rcv,
663                                &tp->t_inpcb->inp_socket->so_snd,
664                                TCP_LOG_LRO, 0,
665                                0, &log, false, &tv);
666         }
667 }
668 #endif
669
670 static inline void
671 tcp_lro_assign_and_checksum_16(uint16_t *ptr, uint16_t value, uint16_t *psum)
672 {
673         uint32_t csum;
674
675         csum = 0xffff - *ptr + value;
676         while (csum > 0xffff)
677                 csum = (csum >> 16) + (csum & 0xffff);
678         *ptr = value;
679         *psum = csum;
680 }
681
682 static uint16_t
683 tcp_lro_update_checksum(const struct lro_parser *pa, const struct lro_entry *le,
684     uint16_t payload_len, uint16_t delta_sum)
685 {
686         uint32_t csum;
687         uint16_t tlen;
688         uint16_t temp[5] = {};
689
690         switch (pa->data.lro_type) {
691         case LRO_TYPE_IPV4_TCP:
692                 /* Compute new IPv4 length. */
693                 tlen = (pa->ip4->ip_hl << 2) + (pa->tcp->th_off << 2) + payload_len;
694                 tcp_lro_assign_and_checksum_16(&pa->ip4->ip_len, htons(tlen), &temp[0]);
695
696                 /* Subtract delta from current IPv4 checksum. */
697                 csum = pa->ip4->ip_sum + 0xffff - temp[0];
698                 while (csum > 0xffff)
699                         csum = (csum >> 16) + (csum & 0xffff);
700                 tcp_lro_assign_and_checksum_16(&pa->ip4->ip_sum, csum, &temp[1]);
701                 goto update_tcp_header;
702
703         case LRO_TYPE_IPV6_TCP:
704                 /* Compute new IPv6 length. */
705                 tlen = (pa->tcp->th_off << 2) + payload_len;
706                 tcp_lro_assign_and_checksum_16(&pa->ip6->ip6_plen, htons(tlen), &temp[0]);
707                 goto update_tcp_header;
708
709         case LRO_TYPE_IPV4_UDP:
710                 /* Compute new IPv4 length. */
711                 tlen = (pa->ip4->ip_hl << 2) + sizeof(*pa->udp) + payload_len;
712                 tcp_lro_assign_and_checksum_16(&pa->ip4->ip_len, htons(tlen), &temp[0]);
713
714                 /* Subtract delta from current IPv4 checksum. */
715                 csum = pa->ip4->ip_sum + 0xffff - temp[0];
716                 while (csum > 0xffff)
717                         csum = (csum >> 16) + (csum & 0xffff);
718                 tcp_lro_assign_and_checksum_16(&pa->ip4->ip_sum, csum, &temp[1]);
719                 goto update_udp_header;
720
721         case LRO_TYPE_IPV6_UDP:
722                 /* Compute new IPv6 length. */
723                 tlen = sizeof(*pa->udp) + payload_len;
724                 tcp_lro_assign_and_checksum_16(&pa->ip6->ip6_plen, htons(tlen), &temp[0]);
725                 goto update_udp_header;
726
727         default:
728                 return (0);
729         }
730
731 update_tcp_header:
732         /* Compute current TCP header checksum. */
733         temp[2] = tcp_lro_rx_csum_tcphdr(pa->tcp);
734
735         /* Incorporate the latest ACK into the TCP header. */
736         pa->tcp->th_ack = le->ack_seq;
737         pa->tcp->th_win = le->window;
738
739         /* Incorporate latest timestamp into the TCP header. */
740         if (le->timestamp != 0) {
741                 uint32_t *ts_ptr;
742
743                 ts_ptr = (uint32_t *)(pa->tcp + 1);
744                 ts_ptr[1] = htonl(le->tsval);
745                 ts_ptr[2] = le->tsecr;
746         }
747
748         /* Compute new TCP header checksum. */
749         temp[3] = tcp_lro_rx_csum_tcphdr(pa->tcp);
750
751         /* Compute new TCP checksum. */
752         csum = pa->tcp->th_sum + 0xffff - delta_sum +
753             0xffff - temp[0] + 0xffff - temp[3] + temp[2];
754         while (csum > 0xffff)
755                 csum = (csum >> 16) + (csum & 0xffff);
756
757         /* Assign new TCP checksum. */
758         tcp_lro_assign_and_checksum_16(&pa->tcp->th_sum, csum, &temp[4]);
759
760         /* Compute all modififications affecting next checksum. */
761         csum = temp[0] + temp[1] + 0xffff - temp[2] +
762             temp[3] + temp[4] + delta_sum;
763         while (csum > 0xffff)
764                 csum = (csum >> 16) + (csum & 0xffff);
765
766         /* Return delta checksum to next stage, if any. */
767         return (csum);
768
769 update_udp_header:
770         tlen = sizeof(*pa->udp) + payload_len;
771         /* Assign new UDP length and compute checksum delta. */
772         tcp_lro_assign_and_checksum_16(&pa->udp->uh_ulen, htons(tlen), &temp[2]);
773
774         /* Check if there is a UDP checksum. */
775         if (__predict_false(pa->udp->uh_sum != 0)) {
776                 /* Compute new UDP checksum. */
777                 csum = pa->udp->uh_sum + 0xffff - delta_sum +
778                     0xffff - temp[0] + 0xffff - temp[2];
779                 while (csum > 0xffff)
780                         csum = (csum >> 16) + (csum & 0xffff);
781                 /* Assign new UDP checksum. */
782                 tcp_lro_assign_and_checksum_16(&pa->udp->uh_sum, csum, &temp[3]);
783         }
784
785         /* Compute all modififications affecting next checksum. */
786         csum = temp[0] + temp[1] + temp[2] + temp[3] + delta_sum;
787         while (csum > 0xffff)
788                 csum = (csum >> 16) + (csum & 0xffff);
789
790         /* Return delta checksum to next stage, if any. */
791         return (csum);
792 }
793
794 static void
795 tcp_flush_out_entry(struct lro_ctrl *lc, struct lro_entry *le)
796 {
797         /* Check if we need to recompute any checksums. */
798         if (le->needs_merge) {
799                 uint16_t csum;
800
801                 switch (le->inner.data.lro_type) {
802                 case LRO_TYPE_IPV4_TCP:
803                         csum = tcp_lro_update_checksum(&le->inner, le,
804                             le->m_head->m_pkthdr.lro_tcp_d_len,
805                             le->m_head->m_pkthdr.lro_tcp_d_csum);
806                         csum = tcp_lro_update_checksum(&le->outer, NULL,
807                             le->m_head->m_pkthdr.lro_tcp_d_len +
808                             le->inner.total_hdr_len, csum);
809                         le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
810                             CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID;
811                         le->m_head->m_pkthdr.csum_data = 0xffff;
812                         if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
813                                 le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
814                         break;
815                 case LRO_TYPE_IPV6_TCP:
816                         csum = tcp_lro_update_checksum(&le->inner, le,
817                             le->m_head->m_pkthdr.lro_tcp_d_len,
818                             le->m_head->m_pkthdr.lro_tcp_d_csum);
819                         csum = tcp_lro_update_checksum(&le->outer, NULL,
820                             le->m_head->m_pkthdr.lro_tcp_d_len +
821                             le->inner.total_hdr_len, csum);
822                         le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
823                             CSUM_PSEUDO_HDR;
824                         le->m_head->m_pkthdr.csum_data = 0xffff;
825                         if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
826                                 le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
827                         break;
828                 case LRO_TYPE_NONE:
829                         switch (le->outer.data.lro_type) {
830                         case LRO_TYPE_IPV4_TCP:
831                                 csum = tcp_lro_update_checksum(&le->outer, le,
832                                     le->m_head->m_pkthdr.lro_tcp_d_len,
833                                     le->m_head->m_pkthdr.lro_tcp_d_csum);
834                                 le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
835                                     CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID;
836                                 le->m_head->m_pkthdr.csum_data = 0xffff;
837                                 if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
838                                         le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
839                                 break;
840                         case LRO_TYPE_IPV6_TCP:
841                                 csum = tcp_lro_update_checksum(&le->outer, le,
842                                     le->m_head->m_pkthdr.lro_tcp_d_len,
843                                     le->m_head->m_pkthdr.lro_tcp_d_csum);
844                                 le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
845                                     CSUM_PSEUDO_HDR;
846                                 le->m_head->m_pkthdr.csum_data = 0xffff;
847                                 if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
848                                         le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
849                                 break;
850                         default:
851                                 break;
852                         }
853                         break;
854                 default:
855                         break;
856                 }
857         }
858
859         /*
860          * Break any chain, this is not set to NULL on the singleton
861          * case m_nextpkt points to m_head. Other case set them
862          * m_nextpkt to NULL in push_and_replace.
863          */
864         le->m_head->m_nextpkt = NULL;
865         lc->lro_queued += le->m_head->m_pkthdr.lro_nsegs;
866         (*lc->ifp->if_input)(lc->ifp, le->m_head);
867 }
868
869 static void
870 tcp_set_entry_to_mbuf(struct lro_ctrl *lc, struct lro_entry *le,
871     struct mbuf *m, struct tcphdr *th)
872 {
873         uint32_t *ts_ptr;
874         uint16_t tcp_data_len;
875         uint16_t tcp_opt_len;
876
877         ts_ptr = (uint32_t *)(th + 1);
878         tcp_opt_len = (th->th_off << 2);
879         tcp_opt_len -= sizeof(*th);
880
881         /* Check if there is a timestamp option. */
882         if (tcp_opt_len == 0 ||
883             __predict_false(tcp_opt_len != TCPOLEN_TSTAMP_APPA ||
884             *ts_ptr != TCP_LRO_TS_OPTION)) {
885                 /* We failed to find the timestamp option. */
886                 le->timestamp = 0;
887         } else {
888                 le->timestamp = 1;
889                 le->tsval = ntohl(*(ts_ptr + 1));
890                 le->tsecr = *(ts_ptr + 2);
891         }
892
893         tcp_data_len = m->m_pkthdr.lro_tcp_d_len;
894
895         /* Pull out TCP sequence numbers and window size. */
896         le->next_seq = ntohl(th->th_seq) + tcp_data_len;
897         le->ack_seq = th->th_ack;
898         le->window = th->th_win;
899         le->flags = th->th_flags;
900         le->needs_merge = 0;
901
902         /* Setup new data pointers. */
903         le->m_head = m;
904         le->m_tail = m_last(m);
905 }
906
907 static void
908 tcp_push_and_replace(struct lro_ctrl *lc, struct lro_entry *le, struct mbuf *m)
909 {
910         struct lro_parser *pa;
911
912         /*
913          * Push up the stack of the current entry
914          * and replace it with "m".
915          */
916         struct mbuf *msave;
917
918         /* Grab off the next and save it */
919         msave = le->m_head->m_nextpkt;
920         le->m_head->m_nextpkt = NULL;
921
922         /* Now push out the old entry */
923         tcp_flush_out_entry(lc, le);
924
925         /* Re-parse new header, should not fail. */
926         pa = tcp_lro_parser(m, &le->outer, &le->inner, false);
927         KASSERT(pa != NULL,
928             ("tcp_push_and_replace: LRO parser failed on m=%p\n", m));
929
930         /*
931          * Now to replace the data properly in the entry
932          * we have to reset the TCP header and
933          * other fields.
934          */
935         tcp_set_entry_to_mbuf(lc, le, m, pa->tcp);
936
937         /* Restore the next list */
938         m->m_nextpkt = msave;
939 }
940
941 static void
942 tcp_lro_mbuf_append_pkthdr(struct lro_entry *le, const struct mbuf *p)
943 {
944         struct mbuf *m;
945         uint32_t csum;
946
947         m = le->m_head;
948         if (m->m_pkthdr.lro_nsegs == 1) {
949                 /* Compute relative checksum. */
950                 csum = p->m_pkthdr.lro_tcp_d_csum;
951         } else {
952                 /* Merge TCP data checksums. */
953                 csum = (uint32_t)m->m_pkthdr.lro_tcp_d_csum +
954                     (uint32_t)p->m_pkthdr.lro_tcp_d_csum;
955                 while (csum > 0xffff)
956                         csum = (csum >> 16) + (csum & 0xffff);
957         }
958
959         /* Update various counters. */
960         m->m_pkthdr.len += p->m_pkthdr.lro_tcp_d_len;
961         m->m_pkthdr.lro_tcp_d_csum = csum;
962         m->m_pkthdr.lro_tcp_d_len += p->m_pkthdr.lro_tcp_d_len;
963         m->m_pkthdr.lro_nsegs += p->m_pkthdr.lro_nsegs;
964         le->needs_merge = 1;
965 }
966
967 static void
968 tcp_lro_condense(struct lro_ctrl *lc, struct lro_entry *le)
969 {
970         /*
971          * Walk through the mbuf chain we
972          * have on tap and compress/condense
973          * as required.
974          */
975         uint32_t *ts_ptr;
976         struct mbuf *m;
977         struct tcphdr *th;
978         uint32_t tcp_data_len_total;
979         uint32_t tcp_data_seg_total;
980         uint16_t tcp_data_len;
981         uint16_t tcp_opt_len;
982
983         /*
984          * First we must check the lead (m_head)
985          * we must make sure that it is *not*
986          * something that should be sent up
987          * right away (sack etc).
988          */
989 again:
990         m = le->m_head->m_nextpkt;
991         if (m == NULL) {
992                 /* Just one left. */
993                 return;
994         }
995
996         th = tcp_lro_get_th(m);
997         tcp_opt_len = (th->th_off << 2);
998         tcp_opt_len -= sizeof(*th);
999         ts_ptr = (uint32_t *)(th + 1);
1000
1001         if (tcp_opt_len != 0 && __predict_false(tcp_opt_len != TCPOLEN_TSTAMP_APPA ||
1002             *ts_ptr != TCP_LRO_TS_OPTION)) {
1003                 /*
1004                  * Its not the timestamp. We can't
1005                  * use this guy as the head.
1006                  */
1007                 le->m_head->m_nextpkt = m->m_nextpkt;
1008                 tcp_push_and_replace(lc, le, m);
1009                 goto again;
1010         }
1011         if ((th->th_flags & ~(TH_ACK | TH_PUSH)) != 0) {
1012                 /*
1013                  * Make sure that previously seen segments/ACKs are delivered
1014                  * before this segment, e.g. FIN.
1015                  */
1016                 le->m_head->m_nextpkt = m->m_nextpkt;
1017                 tcp_push_and_replace(lc, le, m);
1018                 goto again;
1019         }
1020         while((m = le->m_head->m_nextpkt) != NULL) {
1021                 /*
1022                  * condense m into le, first
1023                  * pull m out of the list.
1024                  */
1025                 le->m_head->m_nextpkt = m->m_nextpkt;
1026                 m->m_nextpkt = NULL;
1027                 /* Setup my data */
1028                 tcp_data_len = m->m_pkthdr.lro_tcp_d_len;
1029                 th = tcp_lro_get_th(m);
1030                 ts_ptr = (uint32_t *)(th + 1);
1031                 tcp_opt_len = (th->th_off << 2);
1032                 tcp_opt_len -= sizeof(*th);
1033                 tcp_data_len_total = le->m_head->m_pkthdr.lro_tcp_d_len + tcp_data_len;
1034                 tcp_data_seg_total = le->m_head->m_pkthdr.lro_nsegs + m->m_pkthdr.lro_nsegs;
1035
1036                 if (tcp_data_seg_total >= lc->lro_ackcnt_lim ||
1037                     tcp_data_len_total >= lc->lro_length_lim) {
1038                         /* Flush now if appending will result in overflow. */
1039                         tcp_push_and_replace(lc, le, m);
1040                         goto again;
1041                 }
1042                 if (tcp_opt_len != 0 &&
1043                     __predict_false(tcp_opt_len != TCPOLEN_TSTAMP_APPA ||
1044                     *ts_ptr != TCP_LRO_TS_OPTION)) {
1045                         /*
1046                          * Maybe a sack in the new one? We need to
1047                          * start all over after flushing the
1048                          * current le. We will go up to the beginning
1049                          * and flush it (calling the replace again possibly
1050                          * or just returning).
1051                          */
1052                         tcp_push_and_replace(lc, le, m);
1053                         goto again;
1054                 }
1055                 if ((th->th_flags & ~(TH_ACK | TH_PUSH)) != 0) {
1056                         tcp_push_and_replace(lc, le, m);
1057                         goto again;
1058                 }
1059                 if (tcp_opt_len != 0) {
1060                         uint32_t tsval = ntohl(*(ts_ptr + 1));
1061                         /* Make sure timestamp values are increasing. */
1062                         if (TSTMP_GT(le->tsval, tsval))  {
1063                                 tcp_push_and_replace(lc, le, m);
1064                                 goto again;
1065                         }
1066                         le->tsval = tsval;
1067                         le->tsecr = *(ts_ptr + 2);
1068                 }
1069                 /* Try to append the new segment. */
1070                 if (__predict_false(ntohl(th->th_seq) != le->next_seq ||
1071                                     ((th->th_flags & TH_ACK) !=
1072                                       (le->flags & TH_ACK)) ||
1073                                     (tcp_data_len == 0 &&
1074                                      le->ack_seq == th->th_ack &&
1075                                      le->window == th->th_win))) {
1076                         /* Out of order packet, non-ACK + ACK or dup ACK. */
1077                         tcp_push_and_replace(lc, le, m);
1078                         goto again;
1079                 }
1080                 if (tcp_data_len != 0 ||
1081                     SEQ_GT(ntohl(th->th_ack), ntohl(le->ack_seq))) {
1082                         le->next_seq += tcp_data_len;
1083                         le->ack_seq = th->th_ack;
1084                         le->window = th->th_win;
1085                         le->needs_merge = 1;
1086                 } else if (th->th_ack == le->ack_seq) {
1087                         if (WIN_GT(th->th_win, le->window)) {
1088                                 le->window = th->th_win;
1089                                 le->needs_merge = 1;
1090                         }
1091                 }
1092
1093                 if (tcp_data_len == 0) {
1094                         m_freem(m);
1095                         continue;
1096                 }
1097
1098                 /* Merge TCP data checksum and length to head mbuf. */
1099                 tcp_lro_mbuf_append_pkthdr(le, m);
1100
1101                 /*
1102                  * Adjust the mbuf so that m_data points to the first byte of
1103                  * the ULP payload.  Adjust the mbuf to avoid complications and
1104                  * append new segment to existing mbuf chain.
1105                  */
1106                 m_adj(m, m->m_pkthdr.len - tcp_data_len);
1107                 m_demote_pkthdr(m);
1108                 le->m_tail->m_next = m;
1109                 le->m_tail = m_last(m);
1110         }
1111 }
1112
1113 #ifdef TCPHPTS
1114 static void
1115 tcp_queue_pkts(struct inpcb *inp, struct tcpcb *tp, struct lro_entry *le)
1116 {
1117         INP_WLOCK_ASSERT(inp);
1118         if (tp->t_in_pkt == NULL) {
1119                 /* Nothing yet there */
1120                 tp->t_in_pkt = le->m_head;
1121                 tp->t_tail_pkt = le->m_last_mbuf;
1122         } else {
1123                 /* Already some there */
1124                 tp->t_tail_pkt->m_nextpkt = le->m_head;
1125                 tp->t_tail_pkt = le->m_last_mbuf;
1126         }
1127         le->m_head = NULL;
1128         le->m_last_mbuf = NULL;
1129 }
1130
1131 static struct mbuf *
1132 tcp_lro_get_last_if_ackcmp(struct lro_ctrl *lc, struct lro_entry *le,
1133     struct inpcb *inp, int32_t *new_m)
1134 {
1135         struct tcpcb *tp;
1136         struct mbuf *m;
1137
1138         tp = intotcpcb(inp);
1139         if (__predict_false(tp == NULL))
1140                 return (NULL);
1141
1142         /* Look at the last mbuf if any in queue */
1143         m = tp->t_tail_pkt;
1144         if (m != NULL && (m->m_flags & M_ACKCMP) != 0) {
1145                 if (M_TRAILINGSPACE(m) >= sizeof(struct tcp_ackent)) {
1146                         tcp_lro_log(tp, lc, le, NULL, 23, 0, 0, 0, 0);
1147                         *new_m = 0;
1148                         counter_u64_add(tcp_extra_mbuf, 1);
1149                         return (m);
1150                 } else {
1151                         /* Mark we ran out of space */
1152                         inp->inp_flags2 |= INP_MBUF_L_ACKS;
1153                 }
1154         }
1155         /* Decide mbuf size. */
1156         if (inp->inp_flags2 & INP_MBUF_L_ACKS)
1157                 m = m_getcl(M_NOWAIT, MT_DATA, M_ACKCMP | M_PKTHDR);
1158         else
1159                 m = m_gethdr(M_NOWAIT, MT_DATA);
1160
1161         if (__predict_false(m == NULL)) {
1162                 counter_u64_add(tcp_would_have_but, 1);
1163                 return (NULL);
1164         }
1165         counter_u64_add(tcp_comp_total, 1);
1166         m->m_flags |= M_ACKCMP;
1167         *new_m = 1;
1168         return (m);
1169 }
1170
1171 static struct inpcb *
1172 tcp_lro_lookup(struct ifnet *ifp, struct lro_parser *pa)
1173 {
1174         struct inpcb *inp;
1175
1176         switch (pa->data.lro_type) {
1177 #ifdef INET6
1178         case LRO_TYPE_IPV6_TCP:
1179                 inp = in6_pcblookup(&V_tcbinfo,
1180                     &pa->data.s_addr.v6,
1181                     pa->data.s_port,
1182                     &pa->data.d_addr.v6,
1183                     pa->data.d_port,
1184                     INPLOOKUP_WLOCKPCB,
1185                     ifp);
1186                 break;
1187 #endif
1188 #ifdef INET
1189         case LRO_TYPE_IPV4_TCP:
1190                 inp = in_pcblookup(&V_tcbinfo,
1191                     pa->data.s_addr.v4,
1192                     pa->data.s_port,
1193                     pa->data.d_addr.v4,
1194                     pa->data.d_port,
1195                     INPLOOKUP_WLOCKPCB,
1196                     ifp);
1197                 break;
1198 #endif
1199         default:
1200                 inp = NULL;
1201                 break;
1202         }
1203         return (inp);
1204 }
1205
1206 static inline bool
1207 tcp_lro_ack_valid(struct mbuf *m, struct tcphdr *th, uint32_t **ppts, bool *other_opts)
1208 {
1209         /*
1210          * This function returns two bits of valuable information.
1211          * a) Is what is present capable of being ack-compressed,
1212          *    we can ack-compress if there is no options or just
1213          *    a timestamp option, and of course the th_flags must
1214          *    be correct as well.
1215          * b) Our other options present such as SACK. This is
1216          *    used to determine if we want to wakeup or not.
1217          */
1218         bool ret = true;
1219
1220         switch (th->th_off << 2) {
1221         case (sizeof(*th) + TCPOLEN_TSTAMP_APPA):
1222                 *ppts = (uint32_t *)(th + 1);
1223                 /* Check if we have only one timestamp option. */
1224                 if (**ppts == TCP_LRO_TS_OPTION)
1225                         *other_opts = false;
1226                 else {
1227                         *other_opts = true;
1228                         ret = false;
1229                 }
1230                 break;
1231         case (sizeof(*th)):
1232                 /* No options. */
1233                 *ppts = NULL;
1234                 *other_opts = false;
1235                 break;
1236         default:
1237                 *ppts = NULL;
1238                 *other_opts = true;
1239                 ret = false;
1240                 break;
1241         }
1242         /* For ACKCMP we only accept ACK, PUSH, ECE and CWR. */
1243         if ((th->th_flags & ~(TH_ACK | TH_PUSH | TH_ECE | TH_CWR)) != 0)
1244                 ret = false;
1245         /* If it has data on it we cannot compress it */
1246         if (m->m_pkthdr.lro_tcp_d_len)
1247                 ret = false;
1248
1249         /* ACK flag must be set. */
1250         if (!(th->th_flags & TH_ACK))
1251                 ret = false;
1252         return (ret);
1253 }
1254
1255 static int
1256 tcp_lro_flush_tcphpts(struct lro_ctrl *lc, struct lro_entry *le)
1257 {
1258         struct inpcb *inp;
1259         struct tcpcb *tp;
1260         struct mbuf **pp, *cmp, *mv_to;
1261         bool bpf_req, should_wake;
1262
1263         /* Check if packet doesn't belongs to our network interface. */
1264         if ((tcplro_stacks_wanting_mbufq == 0) ||
1265             (le->outer.data.vlan_id != 0) ||
1266             (le->inner.data.lro_type != LRO_TYPE_NONE))
1267                 return (TCP_LRO_CANNOT);
1268
1269 #ifdef INET6
1270         /*
1271          * Be proactive about unspecified IPv6 address in source. As
1272          * we use all-zero to indicate unbounded/unconnected pcb,
1273          * unspecified IPv6 address can be used to confuse us.
1274          *
1275          * Note that packets with unspecified IPv6 destination is
1276          * already dropped in ip6_input.
1277          */
1278         if (__predict_false(le->outer.data.lro_type == LRO_TYPE_IPV6_TCP &&
1279             IN6_IS_ADDR_UNSPECIFIED(&le->outer.data.s_addr.v6)))
1280                 return (TCP_LRO_CANNOT);
1281
1282         if (__predict_false(le->inner.data.lro_type == LRO_TYPE_IPV6_TCP &&
1283             IN6_IS_ADDR_UNSPECIFIED(&le->inner.data.s_addr.v6)))
1284                 return (TCP_LRO_CANNOT);
1285 #endif
1286         /* Lookup inp, if any. */
1287         inp = tcp_lro_lookup(lc->ifp,
1288             (le->inner.data.lro_type == LRO_TYPE_NONE) ? &le->outer : &le->inner);
1289         if (inp == NULL)
1290                 return (TCP_LRO_CANNOT);
1291
1292         counter_u64_add(tcp_inp_lro_locks_taken, 1);
1293
1294         /* Get TCP control structure. */
1295         tp = intotcpcb(inp);
1296
1297         /* Check if the inp is dead, Jim. */
1298         if (tp == NULL ||
1299             (inp->inp_flags & (INP_DROPPED | INP_TIMEWAIT)) ||
1300             (inp->inp_flags2 & INP_FREED)) {
1301                 INP_WUNLOCK(inp);
1302                 return (TCP_LRO_CANNOT);
1303         }
1304         if ((inp->inp_irq_cpu_set == 0)  && (lc->lro_cpu_is_set == 1)) {
1305                 inp->inp_irq_cpu = lc->lro_last_cpu;
1306                 inp->inp_irq_cpu_set = 1;
1307         }
1308         /* Check if the transport doesn't support the needed optimizations. */
1309         if ((inp->inp_flags2 & (INP_SUPPORTS_MBUFQ | INP_MBUF_ACKCMP)) == 0) {
1310                 INP_WUNLOCK(inp);
1311                 return (TCP_LRO_CANNOT);
1312         }
1313
1314         if (inp->inp_flags2 & INP_MBUF_QUEUE_READY)
1315                 should_wake = false;
1316         else
1317                 should_wake = true;
1318         /* Check if packets should be tapped to BPF. */
1319         bpf_req = bpf_peers_present(lc->ifp->if_bpf);
1320
1321         /* Strip and compress all the incoming packets. */
1322         cmp = NULL;
1323         for (pp = &le->m_head; *pp != NULL; ) {
1324                 mv_to = NULL;
1325                 if (do_bpf_strip_and_compress(inp, lc, le, pp,
1326                          &cmp, &mv_to, &should_wake, bpf_req ) == false) {
1327                         /* Advance to next mbuf. */
1328                         pp = &(*pp)->m_nextpkt;
1329                 } else if (mv_to != NULL) {
1330                         /* We are asked to move pp up */
1331                         pp = &mv_to->m_nextpkt;
1332                 }
1333         }
1334         /* Update "m_last_mbuf", if any. */
1335         if (pp == &le->m_head)
1336                 le->m_last_mbuf = *pp;
1337         else
1338                 le->m_last_mbuf = __containerof(pp, struct mbuf, m_nextpkt);
1339
1340         /* Check if any data mbufs left. */
1341         if (le->m_head != NULL) {
1342                 counter_u64_add(tcp_inp_lro_direct_queue, 1);
1343                 tcp_lro_log(tp, lc, le, NULL, 22, 1,
1344                             inp->inp_flags2, inp->inp_in_input, 1);
1345                 tcp_queue_pkts(inp, tp, le);
1346         }
1347         if (should_wake) {
1348                 /* Wakeup */
1349                 counter_u64_add(tcp_inp_lro_wokeup_queue, 1);
1350                 if ((*tp->t_fb->tfb_do_queued_segments)(inp->inp_socket, tp, 0))
1351                         inp = NULL;
1352         }
1353         if (inp != NULL)
1354                 INP_WUNLOCK(inp);
1355         return (0);     /* Success. */
1356 }
1357 #endif
1358
1359 void
1360 tcp_lro_flush(struct lro_ctrl *lc, struct lro_entry *le)
1361 {
1362         /* Only optimise if there are multiple packets waiting. */
1363 #ifdef TCPHPTS
1364         int error;
1365 #endif
1366
1367         NET_EPOCH_ASSERT();
1368 #ifdef TCPHPTS
1369         CURVNET_SET(lc->ifp->if_vnet);
1370         error = tcp_lro_flush_tcphpts(lc, le);
1371         CURVNET_RESTORE();
1372         if (error != 0) {
1373 #endif
1374                 tcp_lro_condense(lc, le);
1375                 tcp_flush_out_entry(lc, le);
1376 #ifdef TCPHPTS
1377         }
1378 #endif
1379         lc->lro_flushed++;
1380         bzero(le, sizeof(*le));
1381         LIST_INSERT_HEAD(&lc->lro_free, le, next);
1382 }
1383
1384 #ifdef HAVE_INLINE_FLSLL
1385 #define tcp_lro_msb_64(x) (1ULL << (flsll(x) - 1))
1386 #else
1387 static inline uint64_t
1388 tcp_lro_msb_64(uint64_t x)
1389 {
1390         x |= (x >> 1);
1391         x |= (x >> 2);
1392         x |= (x >> 4);
1393         x |= (x >> 8);
1394         x |= (x >> 16);
1395         x |= (x >> 32);
1396         return (x & ~(x >> 1));
1397 }
1398 #endif
1399
1400 /*
1401  * The tcp_lro_sort() routine is comparable to qsort(), except it has
1402  * a worst case complexity limit of O(MIN(N,64)*N), where N is the
1403  * number of elements to sort and 64 is the number of sequence bits
1404  * available. The algorithm is bit-slicing the 64-bit sequence number,
1405  * sorting one bit at a time from the most significant bit until the
1406  * least significant one, skipping the constant bits. This is
1407  * typically called a radix sort.
1408  */
1409 static void
1410 tcp_lro_sort(struct lro_mbuf_sort *parray, uint32_t size)
1411 {
1412         struct lro_mbuf_sort temp;
1413         uint64_t ones;
1414         uint64_t zeros;
1415         uint32_t x;
1416         uint32_t y;
1417
1418 repeat:
1419         /* for small arrays insertion sort is faster */
1420         if (size <= 12) {
1421                 for (x = 1; x < size; x++) {
1422                         temp = parray[x];
1423                         for (y = x; y > 0 && temp.seq < parray[y - 1].seq; y--)
1424                                 parray[y] = parray[y - 1];
1425                         parray[y] = temp;
1426                 }
1427                 return;
1428         }
1429
1430         /* compute sequence bits which are constant */
1431         ones = 0;
1432         zeros = 0;
1433         for (x = 0; x != size; x++) {
1434                 ones |= parray[x].seq;
1435                 zeros |= ~parray[x].seq;
1436         }
1437
1438         /* compute bits which are not constant into "ones" */
1439         ones &= zeros;
1440         if (ones == 0)
1441                 return;
1442
1443         /* pick the most significant bit which is not constant */
1444         ones = tcp_lro_msb_64(ones);
1445
1446         /*
1447          * Move entries having cleared sequence bits to the beginning
1448          * of the array:
1449          */
1450         for (x = y = 0; y != size; y++) {
1451                 /* skip set bits */
1452                 if (parray[y].seq & ones)
1453                         continue;
1454                 /* swap entries */
1455                 temp = parray[x];
1456                 parray[x] = parray[y];
1457                 parray[y] = temp;
1458                 x++;
1459         }
1460
1461         KASSERT(x != 0 && x != size, ("Memory is corrupted\n"));
1462
1463         /* sort zeros */
1464         tcp_lro_sort(parray, x);
1465
1466         /* sort ones */
1467         parray += x;
1468         size -= x;
1469         goto repeat;
1470 }
1471
1472 void
1473 tcp_lro_flush_all(struct lro_ctrl *lc)
1474 {
1475         uint64_t seq;
1476         uint64_t nseq;
1477         unsigned x;
1478
1479         NET_EPOCH_ASSERT();
1480         /* check if no mbufs to flush */
1481         if (lc->lro_mbuf_count == 0)
1482                 goto done;
1483         if (lc->lro_cpu_is_set == 0) {
1484                 if (lc->lro_last_cpu == curcpu) {
1485                         lc->lro_cnt_of_same_cpu++;
1486                         /* Have we reached the threshold to declare a cpu? */
1487                         if (lc->lro_cnt_of_same_cpu > tcp_lro_cpu_set_thresh)
1488                                 lc->lro_cpu_is_set = 1;
1489                 } else {
1490                         lc->lro_last_cpu = curcpu;
1491                         lc->lro_cnt_of_same_cpu = 0;
1492                 }
1493         }
1494         CURVNET_SET(lc->ifp->if_vnet);
1495
1496         /* get current time */
1497         binuptime(&lc->lro_last_queue_time);
1498
1499         /* sort all mbufs according to stream */
1500         tcp_lro_sort(lc->lro_mbuf_data, lc->lro_mbuf_count);
1501
1502         /* input data into LRO engine, stream by stream */
1503         seq = 0;
1504         for (x = 0; x != lc->lro_mbuf_count; x++) {
1505                 struct mbuf *mb;
1506
1507                 /* get mbuf */
1508                 mb = lc->lro_mbuf_data[x].mb;
1509
1510                 /* get sequence number, masking away the packet index */
1511                 nseq = lc->lro_mbuf_data[x].seq & (-1ULL << 24);
1512
1513                 /* check for new stream */
1514                 if (seq != nseq) {
1515                         seq = nseq;
1516
1517                         /* flush active streams */
1518                         tcp_lro_rx_done(lc);
1519                 }
1520
1521                 /* add packet to LRO engine */
1522                 if (tcp_lro_rx_common(lc, mb, 0, false) != 0) {
1523                         /* input packet to network layer */
1524                         (*lc->ifp->if_input)(lc->ifp, mb);
1525                         lc->lro_queued++;
1526                         lc->lro_flushed++;
1527                 }
1528         }
1529         CURVNET_RESTORE();
1530 done:
1531         /* flush active streams */
1532         tcp_lro_rx_done(lc);
1533
1534 #ifdef TCPHPTS
1535         tcp_run_hpts();
1536 #endif
1537         lc->lro_mbuf_count = 0;
1538 }
1539
1540 #ifdef TCPHPTS
1541 static void
1542 build_ack_entry(struct tcp_ackent *ae, struct tcphdr *th, struct mbuf *m,
1543     uint32_t *ts_ptr, uint16_t iptos)
1544 {
1545         /*
1546          * Given a TCP ACK, summarize it down into the small TCP ACK
1547          * entry.
1548          */
1549         ae->timestamp = m->m_pkthdr.rcv_tstmp;
1550         if (m->m_flags & M_TSTMP_LRO)
1551                 ae->flags = TSTMP_LRO;
1552         else if (m->m_flags & M_TSTMP)
1553                 ae->flags = TSTMP_HDWR;
1554         ae->seq = ntohl(th->th_seq);
1555         ae->ack = ntohl(th->th_ack);
1556         ae->flags |= th->th_flags;
1557         if (ts_ptr != NULL) {
1558                 ae->ts_value = ntohl(ts_ptr[1]);
1559                 ae->ts_echo = ntohl(ts_ptr[2]);
1560                 ae->flags |= HAS_TSTMP;
1561         }
1562         ae->win = ntohs(th->th_win);
1563         ae->codepoint = iptos;
1564 }
1565
1566 /*
1567  * Do BPF tap for either ACK_CMP packets or MBUF QUEUE type packets
1568  * and strip all, but the IPv4/IPv6 header.
1569  */
1570 static bool
1571 do_bpf_strip_and_compress(struct inpcb *inp, struct lro_ctrl *lc,
1572     struct lro_entry *le, struct mbuf **pp, struct mbuf **cmp, struct mbuf **mv_to,
1573     bool *should_wake, bool bpf_req)
1574 {
1575         union {
1576                 void *ptr;
1577                 struct ip *ip4;
1578                 struct ip6_hdr *ip6;
1579         } l3;
1580         struct mbuf *m;
1581         struct mbuf *nm;
1582         struct tcphdr *th;
1583         struct tcp_ackent *ack_ent;
1584         uint32_t *ts_ptr;
1585         int32_t n_mbuf;
1586         bool other_opts, can_compress;
1587         uint8_t lro_type;
1588         uint16_t iptos;
1589         int tcp_hdr_offset;
1590         int idx;
1591
1592         /* Get current mbuf. */
1593         m = *pp;
1594
1595         /* Let the BPF see the packet */
1596         if (__predict_false(bpf_req))
1597                 ETHER_BPF_MTAP(lc->ifp, m);
1598
1599         tcp_hdr_offset = m->m_pkthdr.lro_tcp_h_off;
1600         lro_type = le->inner.data.lro_type;
1601         switch (lro_type) {
1602         case LRO_TYPE_NONE:
1603                 lro_type = le->outer.data.lro_type;
1604                 switch (lro_type) {
1605                 case LRO_TYPE_IPV4_TCP:
1606                         tcp_hdr_offset -= sizeof(*le->outer.ip4);
1607                         m->m_pkthdr.lro_etype = ETHERTYPE_IP;
1608                         break;
1609                 case LRO_TYPE_IPV6_TCP:
1610                         tcp_hdr_offset -= sizeof(*le->outer.ip6);
1611                         m->m_pkthdr.lro_etype = ETHERTYPE_IPV6;
1612                         break;
1613                 default:
1614                         goto compressed;
1615                 }
1616                 break;
1617         case LRO_TYPE_IPV4_TCP:
1618                 tcp_hdr_offset -= sizeof(*le->outer.ip4);
1619                 m->m_pkthdr.lro_etype = ETHERTYPE_IP;
1620                 break;
1621         case LRO_TYPE_IPV6_TCP:
1622                 tcp_hdr_offset -= sizeof(*le->outer.ip6);
1623                 m->m_pkthdr.lro_etype = ETHERTYPE_IPV6;
1624                 break;
1625         default:
1626                 goto compressed;
1627         }
1628
1629         MPASS(tcp_hdr_offset >= 0);
1630
1631         m_adj(m, tcp_hdr_offset);
1632         m->m_flags |= M_LRO_EHDRSTRP;
1633         m->m_flags &= ~M_ACKCMP;
1634         m->m_pkthdr.lro_tcp_h_off -= tcp_hdr_offset;
1635
1636         th = tcp_lro_get_th(m);
1637
1638         th->th_sum = 0;         /* TCP checksum is valid. */
1639
1640         /* Check if ACK can be compressed */
1641         can_compress = tcp_lro_ack_valid(m, th, &ts_ptr, &other_opts);
1642
1643         /* Now lets look at the should wake states */
1644         if ((other_opts == true) &&
1645             ((inp->inp_flags2 & INP_DONT_SACK_QUEUE) == 0)) {
1646                 /*
1647                  * If there are other options (SACK?) and the
1648                  * tcp endpoint has not expressly told us it does
1649                  * not care about SACKS, then we should wake up.
1650                  */
1651                 *should_wake = true;
1652         }
1653         /* Is the ack compressable? */
1654         if (can_compress == false)
1655                 goto done;
1656         /* Does the TCP endpoint support ACK compression? */
1657         if ((inp->inp_flags2 & INP_MBUF_ACKCMP) == 0)
1658                 goto done;
1659
1660         /* Lets get the TOS/traffic class field */
1661         l3.ptr = mtod(m, void *);
1662         switch (lro_type) {
1663         case LRO_TYPE_IPV4_TCP:
1664                 iptos = l3.ip4->ip_tos;
1665                 break;
1666         case LRO_TYPE_IPV6_TCP:
1667                 iptos = IPV6_TRAFFIC_CLASS(l3.ip6);
1668                 break;
1669         default:
1670                 iptos = 0;      /* Keep compiler happy. */
1671                 break;
1672         }
1673         /* Now lets get space if we don't have some already */
1674         if (*cmp == NULL) {
1675 new_one:
1676                 nm = tcp_lro_get_last_if_ackcmp(lc, le, inp, &n_mbuf);
1677                 if (__predict_false(nm == NULL))
1678                         goto done;
1679                 *cmp = nm;
1680                 if (n_mbuf) {
1681                         /*
1682                          *  Link in the new cmp ack to our in-order place,
1683                          * first set our cmp ack's next to where we are.
1684                          */
1685                         nm->m_nextpkt = m;
1686                         (*pp) = nm;
1687                         /*
1688                          * Set it up so mv_to is advanced to our
1689                          * compressed ack. This way the caller can
1690                          * advance pp to the right place.
1691                          */
1692                         *mv_to = nm;
1693                         /*
1694                          * Advance it here locally as well.
1695                          */
1696                         pp = &nm->m_nextpkt;
1697                 }
1698         } else {
1699                 /* We have one already we are working on */
1700                 nm = *cmp;
1701                 if (M_TRAILINGSPACE(nm) < sizeof(struct tcp_ackent)) {
1702                         /* We ran out of space */
1703                         inp->inp_flags2 |= INP_MBUF_L_ACKS;
1704                         goto new_one;
1705                 }
1706         }
1707         MPASS(M_TRAILINGSPACE(nm) >= sizeof(struct tcp_ackent));
1708         counter_u64_add(tcp_inp_lro_compressed, 1);
1709         le->compressed++;
1710         /* We can add in to the one on the tail */
1711         ack_ent = mtod(nm, struct tcp_ackent *);
1712         idx = (nm->m_len / sizeof(struct tcp_ackent));
1713         build_ack_entry(&ack_ent[idx], th, m, ts_ptr, iptos);
1714
1715         /* Bump the size of both pkt-hdr and len */
1716         nm->m_len += sizeof(struct tcp_ackent);
1717         nm->m_pkthdr.len += sizeof(struct tcp_ackent);
1718 compressed:
1719         /* Advance to next mbuf before freeing. */
1720         *pp = m->m_nextpkt;
1721         m->m_nextpkt = NULL;
1722         m_freem(m);
1723         return (true);
1724 done:
1725         counter_u64_add(tcp_uncomp_total, 1);
1726         le->uncompressed++;
1727         return (false);
1728 }
1729 #endif
1730
1731 static struct lro_head *
1732 tcp_lro_rx_get_bucket(struct lro_ctrl *lc, struct mbuf *m, struct lro_parser *parser)
1733 {
1734         u_long hash;
1735
1736         if (M_HASHTYPE_ISHASH(m)) {
1737                 hash = m->m_pkthdr.flowid;
1738         } else {
1739                 for (unsigned i = hash = 0; i != LRO_RAW_ADDRESS_MAX; i++)
1740                         hash += parser->data.raw[i];
1741         }
1742         return (&lc->lro_hash[hash % lc->lro_hashsz]);
1743 }
1744
1745 static int
1746 tcp_lro_rx_common(struct lro_ctrl *lc, struct mbuf *m, uint32_t csum, bool use_hash)
1747 {
1748         struct lro_parser pi;   /* inner address data */
1749         struct lro_parser po;   /* outer address data */
1750         struct lro_parser *pa;  /* current parser for TCP stream */
1751         struct lro_entry *le;
1752         struct lro_head *bucket;
1753         struct tcphdr *th;
1754         int tcp_data_len;
1755         int tcp_opt_len;
1756         int error;
1757         uint16_t tcp_data_sum;
1758
1759 #ifdef INET
1760         /* Quickly decide if packet cannot be LRO'ed */
1761         if (__predict_false(V_ipforwarding != 0))
1762                 return (TCP_LRO_CANNOT);
1763 #endif
1764 #ifdef INET6
1765         /* Quickly decide if packet cannot be LRO'ed */
1766         if (__predict_false(V_ip6_forwarding != 0))
1767                 return (TCP_LRO_CANNOT);
1768 #endif
1769
1770         /* We expect a contiguous header [eh, ip, tcp]. */
1771         pa = tcp_lro_parser(m, &po, &pi, true);
1772         if (__predict_false(pa == NULL))
1773                 return (TCP_LRO_NOT_SUPPORTED);
1774
1775         /* We don't expect any padding. */
1776         error = tcp_lro_trim_mbuf_chain(m, pa);
1777         if (__predict_false(error != 0))
1778                 return (error);
1779
1780 #ifdef INET
1781         switch (pa->data.lro_type) {
1782         case LRO_TYPE_IPV4_TCP:
1783                 error = tcp_lro_rx_ipv4(lc, m, pa->ip4);
1784                 if (__predict_false(error != 0))
1785                         return (error);
1786                 break;
1787         default:
1788                 break;
1789         }
1790 #endif
1791         /* If no hardware or arrival stamp on the packet add timestamp */
1792         if ((m->m_flags & (M_TSTMP_LRO | M_TSTMP)) == 0) {
1793                 m->m_pkthdr.rcv_tstmp = bintime2ns(&lc->lro_last_queue_time); 
1794                 m->m_flags |= M_TSTMP_LRO;
1795         }
1796
1797         /* Get pointer to TCP header. */
1798         th = pa->tcp;
1799
1800         /* Don't process SYN packets. */
1801         if (__predict_false(th->th_flags & TH_SYN))
1802                 return (TCP_LRO_CANNOT);
1803
1804         /* Get total TCP header length and compute payload length. */
1805         tcp_opt_len = (th->th_off << 2);
1806         tcp_data_len = m->m_pkthdr.len - ((uint8_t *)th -
1807             (uint8_t *)m->m_data) - tcp_opt_len;
1808         tcp_opt_len -= sizeof(*th);
1809
1810         /* Don't process invalid TCP headers. */
1811         if (__predict_false(tcp_opt_len < 0 || tcp_data_len < 0))
1812                 return (TCP_LRO_CANNOT);
1813
1814         /* Compute TCP data only checksum. */
1815         if (tcp_data_len == 0)
1816                 tcp_data_sum = 0;       /* no data, no checksum */
1817         else if (__predict_false(csum != 0))
1818                 tcp_data_sum = tcp_lro_rx_csum_data(pa, ~csum);
1819         else
1820                 tcp_data_sum = tcp_lro_rx_csum_data(pa, ~th->th_sum);
1821
1822         /* Save TCP info in mbuf. */
1823         m->m_nextpkt = NULL;
1824         m->m_pkthdr.rcvif = lc->ifp;
1825         m->m_pkthdr.lro_tcp_d_csum = tcp_data_sum;
1826         m->m_pkthdr.lro_tcp_d_len = tcp_data_len;
1827         m->m_pkthdr.lro_tcp_h_off = ((uint8_t *)th - (uint8_t *)m->m_data);
1828         m->m_pkthdr.lro_nsegs = 1;
1829
1830         /* Get hash bucket. */
1831         if (!use_hash) {
1832                 bucket = &lc->lro_hash[0];
1833         } else {
1834                 bucket = tcp_lro_rx_get_bucket(lc, m, pa);
1835         }
1836
1837         /* Try to find a matching previous segment. */
1838         LIST_FOREACH(le, bucket, hash_next) {
1839                 /* Compare addresses and ports. */
1840                 if (lro_address_compare(&po.data, &le->outer.data) == false ||
1841                     lro_address_compare(&pi.data, &le->inner.data) == false)
1842                         continue;
1843
1844                 /* Check if no data and old ACK. */
1845                 if (tcp_data_len == 0 &&
1846                     SEQ_LT(ntohl(th->th_ack), ntohl(le->ack_seq))) {
1847                         m_freem(m);
1848                         return (0);
1849                 }
1850
1851                 /* Mark "m" in the last spot. */
1852                 le->m_last_mbuf->m_nextpkt = m;
1853                 /* Now set the tail to "m". */
1854                 le->m_last_mbuf = m;
1855                 return (0);
1856         }
1857
1858         /* Try to find an empty slot. */
1859         if (LIST_EMPTY(&lc->lro_free))
1860                 return (TCP_LRO_NO_ENTRIES);
1861
1862         /* Start a new segment chain. */
1863         le = LIST_FIRST(&lc->lro_free);
1864         LIST_REMOVE(le, next);
1865         tcp_lro_active_insert(lc, bucket, le);
1866
1867         /* Make sure the headers are set. */
1868         le->inner = pi;
1869         le->outer = po;
1870
1871         /* Store time this entry was allocated. */
1872         le->alloc_time = lc->lro_last_queue_time;
1873
1874         tcp_set_entry_to_mbuf(lc, le, m, th);
1875
1876         /* Now set the tail to "m". */
1877         le->m_last_mbuf = m;
1878
1879         return (0);
1880 }
1881
1882 int
1883 tcp_lro_rx(struct lro_ctrl *lc, struct mbuf *m, uint32_t csum)
1884 {
1885         int error;
1886
1887         /* get current time */
1888         binuptime(&lc->lro_last_queue_time);
1889
1890         CURVNET_SET(lc->ifp->if_vnet);
1891         error = tcp_lro_rx_common(lc, m, csum, true);
1892         CURVNET_RESTORE();
1893
1894         return (error);
1895 }
1896
1897 void
1898 tcp_lro_queue_mbuf(struct lro_ctrl *lc, struct mbuf *mb)
1899 {
1900         NET_EPOCH_ASSERT();
1901         /* sanity checks */
1902         if (__predict_false(lc->ifp == NULL || lc->lro_mbuf_data == NULL ||
1903             lc->lro_mbuf_max == 0)) {
1904                 /* packet drop */
1905                 m_freem(mb);
1906                 return;
1907         }
1908
1909         /* check if packet is not LRO capable */
1910         if (__predict_false(mb->m_pkthdr.csum_flags == 0 ||
1911             (lc->ifp->if_capenable & IFCAP_LRO) == 0)) {
1912                 /* input packet to network layer */
1913                 (*lc->ifp->if_input) (lc->ifp, mb);
1914                 return;
1915         }
1916
1917         /* create sequence number */
1918         lc->lro_mbuf_data[lc->lro_mbuf_count].seq =
1919             (((uint64_t)M_HASHTYPE_GET(mb)) << 56) |
1920             (((uint64_t)mb->m_pkthdr.flowid) << 24) |
1921             ((uint64_t)lc->lro_mbuf_count);
1922
1923         /* enter mbuf */
1924         lc->lro_mbuf_data[lc->lro_mbuf_count].mb = mb;
1925
1926         /* flush if array is full */
1927         if (__predict_false(++lc->lro_mbuf_count == lc->lro_mbuf_max))
1928                 tcp_lro_flush_all(lc);
1929 }
1930
1931 /* end */